Python套接字发送第一个消息,但之后不发送任何消息

时间:2018-10-22 07:05:15

标签: python sockets general-network-error

我的套接字发送了第一个消息,但之后没有任何消息。
服务器中的输出:

What do you want to send?

lol

客户收到:

From localhost got message:

lol

然后它不想发送任何其他内容。 我不再打印what do you want to send

我的代码:

server.py文件:

#!/usr/bin/python3
import socket

# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# get local machine name
host = socket.gethostname()
print ("got host name:", host)

port = 9996
print("connecting on port:", port)

# bind to the port
serversocket.bind((host, port))
print("binding host and port")

# queue up to 5 requests
serversocket.listen(5)
print("Waiting for connection")

while True:
    clientsocket, addr = serversocket.accept()
    msg = input("what do you want to send?\n")
    clientsocket.send(msg.encode('ascii'))

client.py文件:

#!/usr/bin/python3
import socket # create a socket object

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine

# name
host = socket.gethostname()
port = 9996 # connection to hostname on the port.

s.connect((host, port)) # Receive no more than 1024 bytes

while True:
    msg = s.recv(1024)
    print(msg.decode("ascii"))

1 个答案:

答案 0 :(得分:1)

客户端仅连接一次(确定),但是服务器在while循环的每次开始时都等待传入连接。

由于客户端不再有连接请求,因此服务器将在第二次迭代中冻结。

如果只想处理一个客户端,请将clientsocket, addr = serversocket.accept()移到while循环之前。如果要处理多个客户端,则标准方法是让服务器接受while循环和spawn a thread for each client内部的连接。

您也可以使用coroutines,但是如果您刚开始使用,可能会有些过头。