Python server receiving only one character from Java client?

I am trying to implement a simple Python server to communicate with some kind of simple Java client code, but I get strange behavior. I am running Mac OSX 10.7.2.

Client Code:

import java.io.*; import java.net.*; public class JavaClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in)); Socket clientSocket = new Socket("localhost", 9999); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine() + '\n'; outToServer.writeBytes(sentence); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } } 

Server Code:

 import SocketServer class PythonServer(SocketServer.BaseRequestHandler): def handle(self): # self.request is the TCP socket connected to the client self.data = self.request.recv(1024).strip() print "{} wrote:".format(self.client_address[0]) print self.data # just send back the same data, but upper-cased self.request.sendall(self.data.upper()) if __name__ == "__main__": HOST, PORT = "localhost", 9999 # Create the server, binding to localhost on port 9999 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever() 

Oddly enough, the first time I create a server instance and send a request from a Java client, everything behaves as expected:

Java Console:

 test FROM SERVER: TEST 

Command line:

 127.0.0.1 wrote: test 

But subsequent queries result in:

Java Console:

 test FROM SERVER: T 

Command line:

 127.0.0.1 wrote: t 

So, it looks like my server is only receiving the first character of my message, even though my client believes that it is sending the entire message.

To complicate matters even further, I created a Java server and a Python client, and the Java client / server command and the Python client / server compiler do not have this problem, but the Python Java client / server does this.

Any ideas?

+4
source share
1 answer

Disable the Nagle algorithm on the client before passing the socket to the DataOutputStream :

 clientSocket.noTcpDelay(true); 

This is somewhat wasteful regarding network bandwidth, but we can also solve this problem if this is a problem for you.

There is another potential problem, this time in your server code, which equals duplication of this question .

+2
source

All Articles