Skip to main content
 首页 » 编程设计

Python 套接字发送第一条消息但之后什么都不发送

2024年12月31日9grandyang

我的套接字发送了第一条消息,但之后什么都没有。
服务器中的输出:

你要发送什么?

哈哈

客户端收到:

从本地主机得到消息:

哈哈

然后它不想发送任何其他内容。 我不再打印 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")) 

请您参考如下方法:

客户端只连接一次(正常),但服务器在每次 while 循环开始时等待传入连接。

由于客户端不再有连接请求,服务器将在第二次迭代时卡住。

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

您还可以使用 coroutines ,但如果您刚刚开始,这可能有点矫枉过正。