2

我的目标是每次客户端向服务器发送数据时,服务器都会显示它。但是目前当客户端发送数据时,服务器捕获数据并仅在第一次显示。是什么导致了问题?顺便说一句,这是我第一次做网络编程,所以请保持你的答案简单。

服务器脚本

import socket

server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.bine(("",5001))
server_socket.listen(5)

print "TCP Server Waiting for incoming client connection on port 5001..."

while True:
    client_socket, address =server_socket.accept()
    print "Connection from ", address
    data = client_socket.recv(512)
    print "RECIEVED:" , data

客户端脚本

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('169.254.0.1', 5001))
data=''
while data!='quit':
        data = raw_input ( "SEND :" )
        client_socket.send(data)
4

2 回答 2

2

您的服务器代码只接收一次,然后接受另一个客户端。您应该循环直到客户端断开连接。(断开连接时,recv()返回空字符串)

while True:
    client_socket, address = server_socket.accept()
    print "Connection from ", address
    while 1:
        data = client_socket.recv(512)
        if not data:
            break
        print "RECIEVED:" , data

顺便说一句,您的服务器代码(和我的代码)一次只处理一个客户端。

于 2013-08-21T09:25:43.570 回答
1
while True:
    client_socket, address =server_socket.accept()
    print "Connection from ", address
    data = client_socket.recv(512)
    print "RECIEVED:" , data

这应该是:

client_socket, address =server_socket.accept()
print "Connection from ", address
while True:
    data = client_socket.recv(512)
    print "RECIEVED:" , data

server_socket.accept()将无限期地等待,直到连接新客户端。实际上,您的循环就像:“接受一个客户并接收一次他发送的数据”。

于 2013-08-21T09:25:28.873 回答