我試圖實現一個簡單的Python服務器與一些簡單的Java客戶端代碼進行通信,但我收到了一些奇怪的行爲。我正在運行Mac OSX 10.7.2。Python服務器只接收來自Java客戶端的一個字符?
客戶端代碼:
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代碼:
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
所以它看起來像我的服務器是唯一接收我的消息的第一個字符,儘管事實上我的消息nt相信它正在發送整個消息。爲了進一步複雜化,我創建了一個Java服務器和Python客戶端,Java客戶端/服務器組合和Python客戶端/服務器組合沒有這個問題,但是Python客戶端/ Java服務器卻沒有這個問題。
任何想法?
嘗試在寫入需要輸出到服務器的數據後刷新你的outToServer。 – GETah
嘗試不使用'BufferedReader' –
@GETah在寫入數據之後,我添加了一行來刷新緩衝區,但是這並沒有'不改變行爲。任何其他想法? – Karen