4

I've tried to test socket connection in Java, but failed. Here is my code (two simple applications, server and client):

public class TestServer {

public static void main(String args[]) throws IOException {
    ServerSocket serverSocket = new ServerSocket(1111);
    System.out.println("Server socket created");
    Socket socket = serverSocket.accept();
    System.out.println("Socket accepted");
    PrintWriter output =  new PrintWriter(socket.getOutputStream(), true);
    System.out.println("Output created");
    output.write("Output string");
    socket.close();
    serverSocket.close();       
}
}

public class TestClient {

public static void main(String args[]) throws IOException {

    Socket socket = new Socket("127.0.0.1", 1111);
    BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    System.out.println("Input: " + input.readLine());
    socket.close();

}

}

Output is (after running a server and, after it, client):

Server socket created
Socket accepted
Output created
Input: null

I've no idea what's the problem and why client didn't receive string sent to it. I'd appreciate any help.

4 Answers 4

6

Usually when I use classes like PrintWriter or OutputStream I need to flush its contents to send the data through a socket or write it to a file.

Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what my problem was. Thanks.
2

input.readLine expects a newline in the input string. Try to replace the output.write with output.println.

I just tested it now and it should work correctly like this.

1 Comment

@Peter Lawrey: yeah, sorry, I was in a rush. Should work now.
2

In addition to all the other comments, you shouldn't close the socket itself, you should close the outermost output stream you have created around the socket's output stream. That will:

(a) flush the output stream (b) close it (c) close the input stream, and (d) close the socket.

Comments

1
//Put the line 

output.flush();

//in the end of the TestServer.java

//and in the TestClient.java I have used the code as given below

Socket socket = new Socket("127.0.0.1", 1111);
    BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String str;
    while((str=input.readLine())!=null){
        System.out.println("Input: " + str);
    }
    socket.close();

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.