2017-05-05 167 views
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; 

有什么不对?

回答

0

您的客户尝试读取线条。行是以\ n结尾的字符串。

clientsocket.send(bytes("ss")) 

所以,你应该送线:

clientsocket.send(bytes("ss\n")) 
相关问题