我有python服务器通过TCP连接服务多个Android客户端。客户端成功连接到服务器并向服务器发送消息,但是它们无法接收服务器的响应(如果它不是回显它们发送的原始消息)。
客户端上的阻塞mServerMessage = mBufferIn.readLine();
一直阻塞,无法捕获服务器的回复。我无法理解我做错了什么。
服务器代码:
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;
有什么问题?
答案 0 :(得分:1)
您的客户尝试读取行。行是以\ n。
结尾的字符串clientsocket.send(bytes("ss"))
所以你应该发一条线:
clientsocket.send(bytes("ss\n"))