2

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

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"))
4

1 回答 1

1

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

由于客户端没有更多的连接请求,服务器将在第二次迭代时冻结。

如果您只想处理单个客户端,请clientsocket, addr = serversocket.accept()while循环之前移动。如果要处理多个客户端,标准方法是让服务器接受while循环内的连接并为每个客户端生成一个线程

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

于 2018-10-22T07:18:50.873 回答