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

标签 python sockets general-network-error

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

你要发送什么?

哈哈

客户端收到:

从本地主机得到消息:

哈哈

然后它不想发送任何其他内容。 我不再打印 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 ,但如果您刚刚开始,这可能有点矫枉过正。

关于Python 套接字发送第一条消息但之后什么都不发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52923915/

相关文章:

javascript - 区分失败(无网络)和 ajax 错误(HTTP 状态代码 0)中的已取消请求

python - 来自 pandas 数据框的输入的 sklearn classification_report 产生 : "TypeError: not all arguments converted during string formatting"

python - 如何打印出基于 3 个列表的特定索引的输出(所有 3 个在列表中的相同位置)

java - 当套接字读取java中的输入时,While循环失败

sockets - 比特流协议(protocol)。同一对等方之间的多次下载

android - 网络上的 WebView 错误::ERR_CONNECTION_REFUSED

python - 找出一个点是否位于点云的凸包中的有效方法是什么?

python - 使用 NGINX 从缓存响应中删除 header

Python:如何识别从哪个套接字接收数据?

双网络上的Mysql错误10061