Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java TCP server not receiving packets until client disconnects

I have a TCP server in Java and a client written in Python. The python client simply sends 10 packets waiting 2 seconds in between each send. However, the java server doesn't seem to recognize the packets until the python script terminates, in which it finally receives all the messages as if they came in at the same time. I have watched with wireshark and verified that the client is sending all the packets correctly.

ServerSocket serverSocket = new ServerSocket(6789); 

Socket clientSocket = null; 
System.out.println ("Waiting for connection.....");

try { 
     clientSocket = serverSocket.accept(); 
} 
catch (IOException e) { 
     System.err.println("Accept failed."); 
     System.exit(1); 
} 

System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");

String data; 

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); 
BufferedReader in = new BufferedReader( 
        new InputStreamReader(clientSocket.getInputStream())); 

while ((data = in.readLine()) != null) { 
    System.out.println ("Server: " + data);         
} 

Python code: import socket import time

TCP_IP = '192.168.1.127'
TCP_PORT = 6789

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((TCP_IP, TCP_PORT))

for i in range(10):
    sock.send("Packet #: %s" % str(i))
    time.sleep(2)

Output I'm seeing:

Connection successful
Waiting for input.....
Server: Packet: #: 0Packet: #: 1Packet: #: 2Packet: #: 3Packet: #: 4Packet: #: 5Packet: #: 6Packet: #: 7Packet: #: 8Packet: #: 9
like image 576
user123959 Avatar asked Jan 21 '26 10:01

user123959


1 Answers

You are using BufferedReader.readLine() in the server... but never sending a new line symbol from the client.

As such, the server doesn't know whether it is going to receive more data in that line, and so has to wait until it is sure that no more data will be sent on that line: closing the socket is one way to indicate that.

Add \n to the end of the packet you send from the client.

sock.send("Packet #: %s\n" % str(i))
like image 104
Andy Turner Avatar answered Jan 22 '26 23:01

Andy Turner