Python简单服务器和客户端脚本(套接字编程)

时间:2013-08-21 09:21:07

标签: python sockets network-programming

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

服务器脚本

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)

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分: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()将无限期等待,直到连接新客户端。实际上你的循环就像:“接受一个客户端并收到他发送的数据一次”。