Reputation: 7357
I'm a newbie in Java network programming and my question may seem too obviously, but suppose I've a client
package com.client.main;
public class Main {
public static void main(String args[]) throws Exception{
Socket s = new Socket("localhost", 12345);
BufferedReader r = new BufferedReader( new InputStreamReader(s.getInputStream()));
System.out.println(r.readLine());
}
}
and server:
package com.server.main;
public class Main {
public static void main(String args[]) throws Exception{
ServerSocket server = new ServerSocket(12345);
Socket client = server.accept();
PrintWriter writer = new PrintWriter(client.getOutputStream());
writer.write("Hello from server");
}
}
I was running the server and after whole server's code has been executed, the client throws an exception without printing any message. Ther is:
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at com.client.main.Main.main(Main.java:14)
Could you explain that behavior?
Upvotes: 0
Views: 673
Reputation: 11697
after whole server's code has been executed
Simple. Your server is done executing so it shut down and the client got a connection reset by peer.
Try putting your server code in an infinite loop so it does not shut down too fast before you appreciate the magic of sockets. Like this,
while(true){
// Your code here
try{
Thread.sleep(10); // Don't forget this!
} catch(InterruptedException ie){
ie.printStackTrace();
}
}
Code explanation: Putting your code in an infinite loop keeps your server program alive. Remember that Java code executes more or less linearly*. The Thread.sleep
is necessary because otherwise your server will hog resources; think of it as your CPU's "breathing time".
Now, to terminate your server, send it a shutdown signal (like kill
or Ctrl+C).
*Once you take into account the things the JVM does behind your back, it is not really linear. It is important to note this fact when doing Sockets because Sockets might eventually lead to Threads, and the things the JVM does is important when you handle concurrency. But for the purposes of a simple client-server program, I think this little handwaving is permissible.
Upvotes: 1