Python服务器只从Java客户端接收一个字符?

我正在尝试实现一个简单的
Python服务器来与一些简单的Java客户端代码进行通信,但我得到了一些奇怪的行为.我正在运行Mac OSX 10.7.2.

客户代码:

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();
    }
}

服务器代码:

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()

奇怪的是,第一次实例化服务器并从Java客户端发送请求时,一切都按预期运行:

Java控制台:

test

FROM SERVER: TEST

命令行:

127.0.0.1 wrote:
test

但随后的请求导致:

Java控制台:

test

FROM SERVER: T

命令行:

127.0.0.1 wrote:
t

所以看起来我的服务器只接收了我的消息的第一个字符,尽管我的客户端认为它正在发送整个消息.

为了进一步复杂化,我创建了一个Java服务器和Python客户端,Java客户端/服务器组合和Python客户端/服务器组合没有这个问题,但是Python客户端/ Java服务器却没有.

有任何想法吗?

最佳答案 在将套接字传递给DataOutputStream之前,在客户端上禁用
Nagle algorithm

clientSocket.noTcpDelay(true);

这对网络带宽有点浪费,但如果这对您来说是个问题,我们也可以解决这个问题.

还有另一个潜在的问题,这次是在您的服务器代码中,这相当于重复
this question

点赞