How to create Java Socket object serving on localhost only? - java

I ask this question again here ( How to create Java socket that is localhost only? ) 'cause all before mentioned methods (simply to say to create one ServerSocket by 3 parameters method) can not solve my problem.
I am working in one big intranet in which, every time when I open one browser, I need enter my proxy account and password to access internet. This is why I hope to test my socket program on localhost.
Occasionally my Client side can connect the Server side, but usually I have to wait for a long time before she coming out. I suppose, it should be related with some of proxy/firewall.
Although I look over all following resources and believe all of them are well worth reading, but I still can not get my issues out.
http://zerioh.tripod.com/ressources/sockets.html
How to determine an incoming connection is from local machine
My Server Side Code
import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.net.InetAddress;
public class Myserver {
private int serverPort = 8000;
private ServerSocket serverSock = null;
public Myserver(int serverPort) {
this.serverPort = serverPort;
try {
/*SocketAddress socketAddress = new InetSocketAddress(InetAddress.getByName("localhost"), serverPort);
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(socketAddress);
serverSocket.accept();*/
serverSock = new ServerSocket(serverPort, 0, InetAddress.getByName(null));
}
catch (IOException e){
e.printStackTrace(System.err);
}
}
public void handleConnection(InputStream sockInput, OutputStream sockOutput) {
while(true) {
byte[] buf=new byte[1024];
int bytes_read = 0;
try {
// This call to read() will wait forever, until the
// program on the other side either sends some data,
// or closes the socket.
bytes_read = sockInput.read(buf, 0, buf.length);
// If the socket is closed, sockInput.read() will return -1.
if(bytes_read < 0) {
System.err.println("Tried to read from socket, read() returned < 0, Closing socket.");
return;
}
System.err.println("Received "+bytes_read
+" bytes, sending them back to client, data="
+(new String(buf, 0, bytes_read)));
sockOutput.write(buf, 0, bytes_read);
// This call to flush() is optional - we're saying go
// ahead and send the data now instead of buffering
// it.
sockOutput.flush();
// sockOutput.close();
}
catch (Exception e){
System.err.println("Exception reading from/writing to socket, e="+e);
e.printStackTrace(System.err);
return;
}
}
}
public void waitForConnections() {
Socket sock = null;
InputStream sockInput = null;
OutputStream sockOutput = null;
while (true) {
try {
// This method call, accept(), blocks and waits
// (forever if necessary) until some other program
// opens a socket connection to our server. When some
// other program opens a connection to our server,
// accept() creates a new socket to represent that
// connection and returns.
sock = serverSock.accept();
System.err.println("Have accepted new socket.");
// From this point on, no new socket connections can
// be made to our server until we call accept() again.
sockInput = sock.getInputStream();
sockOutput = sock.getOutputStream();
}
catch (IOException e){
e.printStackTrace(System.err);
}
// Do something with the socket - read bytes from the
// socket and write them back to the socket until the
// other side closes the connection.
handleConnection(sockInput, sockOutput);
// Now we close the socket.
try {
System.err.println("Closing socket.");
sock.close();
}
catch (Exception e){
System.err.println("Exception while closing socket.");
e.printStackTrace(System.err);
}
System.err.println("Finished with socket, waiting for next connection.");
}
}
}
My Client Side Code
import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class MyClient {
private String serverHostname = null;
private int serverPort =0;
private byte[] data = null;
private Socket sock = null;
private InputStream sockInput = null;
private OutputStream sockOutput = null;
public MyClient(String serverHostname, int serverPort, byte[] data){
this.serverHostname = serverHostname;
this.serverPort = serverPort;
this.data = data;
}
public void sendSomeMessages(int iterations) {
System.err.println("Opening connection to "+serverHostname+" port "+serverPort);
try {
sock = new Socket(serverHostname, serverPort);
sockInput = sock.getInputStream();
sockOutput = sock.getOutputStream();
}
catch (IOException e){
e.printStackTrace(System.err);
return;
}
System.err.println("About to start reading/writing to/from socket.");
byte[] buf = new byte[data.length];
int bytes_read = 0;
for(int loopi = 1; loopi <= iterations; loopi++) {
try {
sockOutput.write(data, 0, data.length);
bytes_read = sockInput.read(buf, 0, buf.length);
}
catch (IOException e){
e.printStackTrace(System.err);
}
if(bytes_read < data.length) {
System.err.println("run: Sent "+data.length+" bytes, server should have sent them back, read "+bytes_read+" bytes, not the same number of bytes.");
}
else {
System.err.println("Sent "+bytes_read+" bytes to server and received them back again, msg = "+(new String(data)));
}
// Sleep for a bit so the action doesn't happen to fast - this is purely for reasons of demonstration, and not required technically.
try { Thread.sleep(50);} catch (Exception e) {};
}
System.err.println("Done reading/writing to/from socket, closing socket.");
try {
sock.close();
}
catch (IOException e){
System.err.println("Exception closing socket.");
e.printStackTrace(System.err);
}
System.err.println("Exiting.");
}
}
My Test Code
import java.net.*;
public class Mytest {
public static void main(String[] args) {
String hostname = "localhost";
int port = 8000;
try {
InetAddress add = InetAddress.getLocalHost();
System.out.println( add);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
byte[] data = "my program".getBytes();
MyClient client = new MyClient(hostname, port, data);
client.sendSomeMessages(10);
Myserver server = new Myserver(port);
server.waitForConnections();
}
}
I try telnet, but I can't connect it at all

The first problem is that the test code runs both the client and the server. In Mytest.main(), the main thread does the following:
Creates a client (I would have thought that this step would fail)
Tries to send some messsages (but no ServerSocket has been started)
The server is created
The server waits forever, blocking the main thread on accept()
As a starter to get your code working. Create two test classes TestServer and TestClient, both of these must have main() methods. Launch TestServer first in it's own Java process. Next launch TestClient in separate Java process. This should work!
After you've got everything working, you should introduce some concurrency into your server. The way that it's currently written it can only serve a single client at a time. Create new threads to manage new sockets returned from accept().
Good luck!

Related

Simple Proxy in Java : POST request exception

I wrote a simple HTTP proxy in java. The code is as follows:
public class SampleProxy {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
int port = 1234;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Port Error");
System.exit(-1);
}
while (listening) {
new ProxyThread(serverSocket.accept()).start();
}
serverSocket.close();
}
}
class ProxyThread extends Thread {
private final Socket clientSocket;
public ProxyThread(Socket socket) {
this.clientSocket = socket;
}
public void run() {
try {
String parts[];
// Read request
InputStream incomingIS = clientSocket.getInputStream();
int incomingLen = incomingIS.available();
byte[] b = new byte[8196];
int len = incomingIS.read(b);
if (len > 0) {
System.out.println("The Request is : \n" + new String(b, 0, len) + "\n*********\n");
Socket socket = new Socket("localhost", 80);
OutputStream outgoingOS = socket.getOutputStream();
outgoingOS.write(b, 0, len);
OutputStream incomingOS = clientSocket.getOutputStream();
InputStream outgoingIS = socket.getInputStream();
int length;
//Read from server
byte[] b2=new byte[8196];
length = outgoingIS.available();
outgoingIS.read(b2);
incomingOS.write(b2, 0, b2.length);
incomingOS.close();
outgoingIS.close();
outgoingOS.close();
incomingIS.close();
socket.close();
} else {
incomingIS.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
Logger.getLogger(ProxyThread.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
As seen, the client requests at port 1234, the proxy forwards the request to the server and gets the response which is then returned back to the client.
In normal scenarios, this works fine, but, I tried testing the same for high traffic scenarios using a shell script which sends multiple(around 50) POST requests, one after another and found out that for some requests, only the headers are getting received. The POST data is omitted but the Content-Length shows the appropriate length of the variables which ought to be sent. This does not happen for specific requests, but at random, maybe 3 or 4 out of 50 Requests.
The same error however, does not seem to exist for GET requests.
Any suggestions as to whats actually causing the error?
Usual mistakes here. Misuse of available(), and failure to actually implement the HTTP protocol correctly. You need to read RFC 2616 thoroughly, especially the parts about request and response length; and reread the Javadoc for InputStream.available(), where you will find a specific warning against using it as you are doing here.

Java Simple EchoServer won't work

I read through SO a lot and I found many examples which were doing what I am trying to do. But I just can't find the issue in my code at all. May be I just need a fresh set of eyes to look at my code.
So with risk of being flagged for duplicate thread here is goes. I have a simple Java code. It opens a port. Connects a socket to that. gets the inputstream and outputstream. Puts some text to output stream and inputstream tries to read the text. When the mehtod for readLine is executed it does not return back to the code. It just keeps running and never comes back to main method.
import java.net.*;
import java.io.*;
import java.io.ObjectInputStream.GetField;
public class echoserver {
public static void main(String[] args) {
// TODO Auto-generated method stub
String hostName = "127.0.0.1";
// InetAddress.getLocalHost()
int portNumber = 5000;
ServerSocket ss = null;
Socket echoSocket = null;
try {
ss = new ServerSocket(portNumber);
echoSocket = new Socket(hostName, portNumber);
// echoSocket = ss.accept();
System.out.println("open");
System.out.println(echoSocket.isBound());
PrintWriter writer = new PrintWriter(echoSocket.getOutputStream());
for (int i = 0; i < 100; i++) {
writer.print("test String");
}
writer.flush();
// writer.close();
System.out.println("inputstream read");
DataInputStream is = new DataInputStream(echoSocket.getInputStream());
String fromStream = is.readLine();
System.out.println(fromStream);
System.out.println("bufferreader read");
BufferedReader reader = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
String fromReader = reader.readLine();
System.out.println(fromReader);
} catch (UnknownHostException ex1) {
// TODO Auto-generated catch block
System.out.println("EX1");
ex1.printStackTrace();
}
catch (IOException ex2) {
// TODO: handle exception
System.out.println("EX2");
ex2.printStackTrace();
}
finally {
try {
echoSocket.close();
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
EDIT : Updated Code below... The only issue in this code is that while loop in Server.Run never ends. I looked for some other attributes (I remember something like isTextAvailable) but could not find it. The idea behind the code is to convert it into a chat client. needless to say its a struggle !
EDIT 2: I found the the issue. I never closed the socket from writer end so the listner kept on listening ! Thanks for help everyone !
clientsocket.close();
Added one line and it worked!
import java.net.*;
import java.io.*;
import java.io.ObjectInputStream.GetField;
import java.util.*;
public class echoserver {
static echoserver echo;
public static class Client implements Runnable {
Socket clientsocket;
String hostName = "127.0.0.1";
int portNumber = 5000;
static int onesleep = 0;
public void run(){
System.out.println("Client Run " + new Date());
try {
clientsocket = new Socket(hostName,portNumber);
PrintWriter writer = new PrintWriter(clientsocket.getOutputStream());
for (int i = 0; i < 10; i++) {
writer.println("test String " + i );
}
writer.flush();
clientsocket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Server implements Runnable {
public void run(){
System.out.println("Server Run" + new Date());
int portNumber = 5000;
ServerSocket ss = null;
Socket serversocket = null;
InputStreamReader streamReader;
try {
ss = new ServerSocket(portNumber);
serversocket = ss.accept();
System.out.println("bufferreader read " + new Date());
streamReader = new InputStreamReader(serversocket.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
String fromReader;
System.out.println(reader.ready());
System.out.println(reader.readLine());
while ((fromReader = reader.readLine()) != null) {
System.out.println(fromReader);
}
System.out.println("After While in Server Run");
} catch (IOException ex_server) {
// TODO Auto-generated catch block
System.out.println("Server Run Error " + new Date());
ex_server.printStackTrace();
}
finally {
try {
serversocket.close();
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("open" + new Date());
System.out.println(serversocket.isBound());
}
}
public void go(){
Server server = new Server();
Thread serverThread = new Thread(server);
serverThread.start();
Client client = new Client();
Thread clientThread = new Thread(client);
clientThread.start();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
echo = new echoserver();
echo.go();
}
}
I had prepared a version of this post earlier, but based on your last comment in the other answer, it seems you have already figured it out. I'll posting this anyways, in case it is of any help.
The broad answer is that your class, as you currently have it, effectively represents both the client-side AND server-side portions within the same thread / process. As you've seen, you're able to write your data to the outbound (or client-side) socket, but the server-side component never gets a chance to listen for incoming connections.
Consequently, when you attempt to read data from the inbound (or server-side) socket's input stream, nothing exists because nothing was received. The readline() method ultimately blocks until data is available, which is why your program seems to hold at that point. Additionally, like haifzhan said, creating a new socket using new Socket(...) doesn't establish the connection, all you have is a socket with nothing in the stream.
The ServerSocket#accept method what you need to use in order to listen for connections. This method will create the socket for you, from which you can attempt to read from its stream. Like haifzhan said, that method blocks until a connection is established, which is ultimately why it cannot function properly in a single-threaded environment.
To do this within the same application, you'll simply need to separate the components and run them in separate threads. Try something like the following:
public class EchoClient {
public static void main(String[] args) throws InterruptedException {
new Thread(new EchoServer()).start(); // start up the server thread
String hostName = "localhost";
int portNumber = 5000;
try {
Socket outboundSocket = new Socket(hostName, portNumber);
System.out.println("Echo client is about to send data to the server...");
PrintWriter writer = new PrintWriter(outboundSocket.getOutputStream());
for (int i = 0; i < 100; i++) {
writer.print("test String");
}
System.out.println("Data has been sent");
writer.flush();
outboundSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And the server component, which operates as a separate thread:
public class EchoServer implements Runnable {
public void run(){
try {
ServerSocket ss = new ServerSocket(5000);
System.out.println("Waiting for connection...");
Socket inboundSocket = ss.accept();
System.out.println("inputstream read");
DataInputStream is = new DataInputStream(inboundSocket.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String fromStream = reader.readLine();
System.out.println(fromStream);
System.out.println("bufferreader read");
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You did not connect to any client side socket...
From Writing the Server Side of a socket:
The accept method waits until a client starts up and requests a
connection on the host and port of this server. When a connection is
requested and successfully established, the accept method returns a
new Socket object which is bound to the same local port and has its
remote address and remote port set to that of the client. The server
can communicate with the client over this new Socket and continue to
listen for client connection requests on the original ServerSocket.
ss = new ServerSocket(portNumber);
echoSocket = new Socket(hostName, portNumber)
// echoSocket = ss.accept();
You should not use new Socket(host, port) to create a echoSocket, the ss.accept() is the correct way to establish the server client connection.
The reason it hangs because your code above(echoSocekt = ss.accept();) is not correct so the following will not be availalbe
DataInputStream is = new DataInputStream(echoSocket.getInputStream());
If you invoke is.available(), it will return 0 which means 0 bytes can be read from.
Read the link I provided, check EchoServer.java and EchoClient.java, and you will estiblish your own connection

Why must I include a Thread.sleep(10) to get data to be sent over a socket

I have the following code for sending data over a socket:
socketclient.java
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClient
implements Runnable
{
private Socket socket;
private String ServerIP = "192.168.0.11";
private static final int ServerPort = 7000;
#Override
public void run()
{
try
{
socket = new Socket(ServerIP, ServerPort);
}
catch(Exception e)
{
System.out.print("Whoops! It didn't work on ip" + ServerIP + "!:");
System.out.print(e.getLocalizedMessage());
System.out.print("\n");
}
}
public void Send(String s)
{
try
{
Thread.sleep(10);
OutputStream out = socket.getOutputStream(); //Starts the output stream
PrintWriter output = new PrintWriter(out);
output.println(s); //sends the data over the socket
output.flush(); //flushes the outputwriter
output.close(); //closes the outputwriter
out.close(); //closes the outputstream
}
catch (UnknownHostException e) {
System.out.print(e.toString());
} catch (IOException e) {
System.out.print(e.toString());
}catch (Exception e) {
System.out.print(e.toString());
}
}
}
When i dont have the sleep in the send function the server output looks like this (i have it set to print the 'conn' and 'addr' of every connection), the server is coded in python
Connected with 192.168.0.11:52578
in client thread
Connected with 192.168.0.11:52579
in client thread
Connected with 192.168.0.11:52609
in client thread
and the server connection data recieveing/main connection thread is this:
def clientthread(conn):
#Sending message to connected client
#Receiving from client
data = conn.recv(4096)
print data
#came out of loop
conn.close()
My goal for the server is to open/close sockets on the client-side everytime i want to send data because i want each reciever to create its own connections using a socket class i created.
What is the reason for having to add a thread.sleep() before sending a string over a TCP socket in java?
Also, this is how i use my Socketclient class:
SMSClient = new SocketClient();
Thread thread = new Thread(SMSClient);
thread.start();
SMSClient.Send(smsData);
When you instantiate a new SocketClient object you are not running the new thread. You should call your Send(String s) method just after socket = new Socket(ServerIP, ServerPort); from inside the run method.
To know the current thread in your running code put some log like the following: Log.d("label", "thread id: "+android.os.Process.myTid()). Try for example to evaluate the current thread inside run method, and inside the Send(String s) method when you call this latter as you are doing and after having moved the call to the method inside the run.
I suggest to use IntentService for your purpose since, when needed, you can managed easily the socket connection and transmission in a separate thread.
When the thread.start() call returns the thread may not have executed yet. And then you are sending already your first request. You may wait with sleep after thread.start() that is better (while sleeping in the main thread the connection thread has a chance to run) - but still not best practice. Here is my working code ( I added a main function to the SocketClient ):
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClient
implements Runnable
{
private Socket socket;
private String ServerIP = "127.0.0.1";
private static final int ServerPort = 7000;
#Override
public void run()
{
try
{
socket = new Socket(ServerIP, ServerPort);
}
catch(Exception e)
{
System.out.print("Whoops! It didn't work on ip" + ServerIP + "!:");
System.out.print(e.getLocalizedMessage());
System.out.print("\n");
}
}
public void Send(String s)
{
try
{
OutputStream out = socket.getOutputStream(); //Starts the output stream
PrintWriter output = new PrintWriter(out);
output.println(s); //sends the data over the socket
output.flush(); //flushes the outputwriter
output.close(); //closes the outputwriter
out.close(); //closes the outputstream
}
catch (UnknownHostException e) {
System.out.print(e.toString());
} catch (IOException e) {
System.out.print(e.toString());
}catch (Exception e) {
System.out.print(e.toString());
}
}
static public void main(String[] args)
{
SocketClient socketClient = new SocketClient();
Thread thread = new Thread(socketClient);
thread.start();
try
{
Thread.sleep(19);
}
catch(Exception e) {}
socketClient.Send("hallo");
}
}

How to fix the UDP server in Java?

I had problem to transfer data over TCP. So i was writing a UDP server, but its not working, shows this following error, how can i fix it?
My error:
run:
UDP Server started
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:657)
at socket.UDPHandler.start(UDPHandler.java:25)
at socket.UDPServer.waitForConnections(UDPServer.java:27)
at socket.UDPServer.main(UDPServer.java:46)
BUILD STOPPED (total time: 14 seconds)
UDPServer.java
package socket;
import java.net.*;
import java.io.*;
public class UDPServer
{
private int serverPort = 0;
private DatagramSocket serverSock = null;
//private Socket sock = null;
public UDPServer(int serverPort) throws IOException
{
this.serverPort = serverPort;
serverSock = new DatagramSocket(serverPort);
System.out.println("UDP Server started");
}
public void waitForConnections()
{
while (true)
{
try {
//sock = serverSock.accept();
//System.err.println("Accepted new socket");
UDPHandler handler = new UDPHandler(serverSock);
handler.start();
}
catch (IOException e){
e.printStackTrace(System.err);
}
}
}
public static void main(String argv[])
{
int port = 8889;
UDPServer server = null;
try {
server = new UDPServer(port);
}
catch (IOException e){
e.printStackTrace(System.err);
}
server.waitForConnections();
}
}
UDPHandler.java
package socket;
import java.io.*;
import java.net.*;
import main.*;
public class UDPHandler implements Runnable
{
private DatagramSocket sock = null;
private DatagramPacket sockInput = null;
private DatagramPacket sockOutput = null;
private Thread myThread = null;
public UDPHandler(DatagramSocket sock) throws IOException
{
this.sock = sock;
//sockInput = new DatagramPacket();
//sockOutput = sock.getOutputStream();
this.myThread = new Thread(this);
}
public void start()
{
myThread.start();
}
public void run()
{
while(true)
{
byte[] buf=new byte[1024];
int bytes_read = 0;
try {
// Incoming - Test
sockInput = new DatagramPacket(buf, buf.length);
sock.receive(sockInput);
bytes_read = sockInput.getLength();
String data = new String(sockInput.getData());
System.err.println("DATA: " + bytes_read + " bytes, data=" +data);
// IP - Test
InetAddress IPAddress = sockInput.getAddress();
int port = sockInput.getPort();
// Sending - Test
sockOutput = new DatagramPacket(data.getBytes(), data.length(), IPAddress, port);
sock.send(sockOutput);
} catch (Exception e) {
e.printStackTrace(System.err);
break;
}
}
try {
System.err.println("Closing socket.");
sock.close();
} catch (Exception e) {
System.err.println("Exception while closing socket, e="+e);
e.printStackTrace(System.err);
}
}
}
You are creating infinite number of threads in while(true) loop in waitForConnection() method. You should call DatagramSocket receive() method within your server (it is blocking operation) and if datagram is received, then delegate its processing to some handler (for example retrieved from thread pool).
I find that the receive() method causes a memory leak. While java waits for UDP packet, my memory usage slowly increases when no other thread is operating. Seems to be increasing memory usage at approx 20kb per hour while running the .receive() method.
Not sure why that would be.
I did not run/debug the code, but the java.lang.OutOfMemoryError makes me think there is something going on inside those while(true) loops, either too many handlers are being created in waitForConnections() (less likely) or too many byte[] buffers are being allocated in run() (more likely).
For the poster, try adding a print statement as the first line of each of those while(true) loops to see how many times they get executed.
It seems odd for the JVM to run out of memory with just a listening UDP server and a simple test application. I hope someone can debug into it and confirm, I can't run the code at the moment.

Java: reconnection on a socket sometimes gives error

I am making a prototype client & server so that I can understand how to handle reconnects.
The server ought to create a serversocket and listen forever. A client may connect, send its data, and close its socket but it will not send a "I'm done and closing" type message to the server. For this reason, the server gets a EOFException when it does a readByte() since the remote client has closed. In the error handler for the EOFException, it will close the socket and open a new one.
Here's the problem: The client sometimes gets a SocketWriteError when it does the outputStream.write() call even after it successfully opens the socket/inputstream/outpustream. It may have something to do with the frequency that I'm opening and closing these sockets. One interesting thing is that the client does an arbitrary number of writes/close/reconnects before crapping out. It will sometimes crap out on the first reconnect, other times it will take 50 reconnects before seeing the SocketWriteError.
Here's the error on the client side:
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:115)
at bytebuffertest.Client.main(Client.java:37)
Here are some snippets of code:
SERVER:
public static void main(String[] args)
{
Server x = new Server();
x.initialize();
}
private void initialize()
{
ServerSocket s;
InputStream is;
DataInputStream dis;
while (true) //ADDED THIS!!!!!!!!!!!!!!!!!!!!!!
{
try
{
s = new ServerSocket(4448);
s.setSoTimeout(0);
s.setReuseAddress(true);
is = s.accept().getInputStream();
System.out.println("accepted client");
dis = new DataInputStream(is);
try
{
byte input = dis.readByte();
System.out.println("read: " + input);
} catch (Exception ex)
{
System.out.println("Exception");
dis.close();
is.close();
s.close();
}
} catch (IOException ex)
{
System.out.println("ioexception");
}
}
}
CLIENT:
public static void main(String[] args)
{
Socket s;
OutputStream os;
try
{
s = new Socket("localhost", 4448);
s.setKeepAlive(true);
s.setReuseAddress(true);
os = s.getOutputStream();
int counter = 0;
while (true)
{
try
{
os.write((byte) counter++);
os.flush();
os.close();
s.close();
s = new Socket("localhost", 4448);
s.setKeepAlive(true);
s.setReuseAddress(true);
os = s.getOutputStream();
} catch (Exception e)
{
e.printStackTrace();
System.err.println("ERROR: reconnecting...");
}
}
} catch (Exception ex)
{
ex.printStackTrace();
System.err.println("ERROR: could not connect");
}
}
Does anyone know how to properly reconnect?
Don't close the ServerSocket on an error, just .accept() a new connection.
What I normally do is each time ServerSocket.accept() returns a Socket, I spawn off a thread to handle sending and receiving from that Socket. That way you're ready to start accepting a new connection as soon as somebody wants to connect to you.

Categories