我正在尝试实现一个简单的 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 服务器有。
有任何想法吗?