0
我有python服務器通過TCP連接服務多個android客戶端。客戶端成功地連接到服務器並將消息發送到服務器,但它們未能接收到服務器的響應(如果它不是回覆它們發送的原始消息)。 客戶端阻止mServerMessage = mBufferIn.readLine();
一直阻塞,無法捕獲服務器的答覆。我不明白我做錯了什麼。 服務器代碼:TCP客戶端不接收服務器的消息
import socket
import thread
import time
TCP_IP = '192.168.1.105'
TCP_PORT = 5004
BUFFER_SIZE = 20 # Normally 1024, but we want fast response
NUMBER_OF_CLIENTS = 2
def on_new_client(clientsocket,addr):
while True:
msg = clientsocket.recv(BUFFER_SIZE)
if not msg: break
print addr, ' >> ', msg, '\n'
#msg = raw_input('SERVER >> ')
clientsocket.send(msg) #If I sent anything other than the original message (for example: clientsocket.send(bytes("ss")) or clientsocket.send("ss")) the client fails to capture it!!
clientsocket.close()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Server started!'
print 'Waiting for clients...'
s.bind((TCP_IP, TCP_PORT))
s.listen(NUMBER_OF_CLIENTS)
while True:
conn, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
thread.start_new_thread(on_new_client,(conn,addr))
s.close()
客戶端代碼:
InetAddress serverAddr = InetAddress.getByName(home.SERVER_IP);
Log.i("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVER_REQUESTS_PORT);
try {
//sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//receives the message which the server sends back -> the number of clients remaining
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i("tcpClient", "mBufferIN" + String.valueOf(mBufferIn));
mServerMessage = mBufferIn.readLine();
//home.remainingCount.setText(mServerMessage);
Log.i("tcpClient", "mBufferIN = " + mServerMessage); //This is never excuted when the message
counterValueRetrieved = true;
while (mRun) {
if (mServerMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(mServerMessage);
}
}
Log.i("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
} catch (Exception e) {
Log.i("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
注意
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;
有什麼不對?