Reputation: 297
I have written a basic program to demonstrate client server interaction. Connection is getting established but unable to fetch the data from stream. It throws an exception stating the connection reset
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
private ServerSocket serverSocket;
private int port;
public SocketServer(int port) {
this.port = port;
}
public void start() throws IOException {
System.out.println("Starting the socket server at port:" + port);
serverSocket = new ServerSocket(port);
System.out.println("Waiting for clients...");
Socket client = serverSocket.accept();
sendWelcomeMessage(client);
}
private void sendWelcomeMessage(Socket client) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write("Hello. You are connected to a Simple Socket Server. What is your name?");
writer.flush();
}
/**
* Creates a SocketServer object and starts the server.
*
* @param args
*/
public static void main(String[] args) {
// Setting a default port number.
int portNumber = 9990;
try {
// initializing the Socket Server
SocketServer socketServer = new SocketServer(portNumber);
socketServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClient {
private String hostname;
private int port;
Socket socketClient;
public SocketClient(String hostname, int port){
this.hostname = hostname;
this.port = port;
}
public void connect() throws UnknownHostException, IOException{
System.out.println("Attempting to connect to "+hostname+":"+port);
socketClient = new Socket(hostname,port);
System.out.println("Connection Established");
}
public void readResponse() throws IOException{
String userInput;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
System.out.println("Response from server:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
}
}
public static void main(String arg[]){
//Creating a SocketClient object
SocketClient client = new SocketClient ("localhost",9990);
try {
//trying to establish connection to the server
client.connect();
//if successful, read response from server
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be up."+e.getMessage());
e.printStackTrace();
}
}
}
##OUTPUT##
Attempting to connect to localhost:9990
Connection Established
Response from server:
Hello. You are connected to a Simple Socket Server. What is your name?
java.net.SocketException: Connection reset
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 SocketClient.readResponse(SocketClient.java:31)
at SocketClient.main(SocketClient.java:45)
Upvotes: 2
Views: 4554
Reputation: 1406
I have actually been wrestling with this for a while as well, but I believe I have found a more accurate answer, and thought I should share it. The original example never closes the BufferedWriter
. So simply add writer.close()
after writer.flush()
, like so:
writer.write("Hello. You are connected to a Simple Socket Server. What is your name?");
writer.flush();
writer.close();
Because it was never closed, the output was never null, so the while
loop was never failing.
Upvotes: 0
Reputation: 16625
There's at least one thing wrong with the current implementation. You utilise readLine()
to get the data - however readLine()
does this:
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Your program that emits the data does not use a newline character to terminate the "message":
writer.write("Hello. You are connected to a Simple Socket Server. What is your name?");
writer.flush();
To terminate the message, add a newline:
writer.write("Hello. You are connected to a Simple Socket Server. What is your name?");
writer.write("\n"); // shown separately for clarity
writer.flush();
Upvotes: 2