Java socket connection

I tried to check socket connections in Java, but could not. 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(); } } 

Exit (after starting the server and after it the client):

 Server socket created Socket accepted Output created Input: null 

I do not know what the problem is and why the client did not receive the string sent to him. I would appreciate any help.

+4
source share
4 answers

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

+6
source

input.readLine expects a new line in the input line. Try replacing output.write with output.println .

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

+2
source

In addition to all the other comments, you should not close the socket itself, you should close the external output stream that you created around the socket output stream. It will be:

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

+2
source
 //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(); } 
+1
source

Source: https://habr.com/ru/post/1386696/


All Articles