【问题标题】:Python socket sends the first message but nothing afterwardPython 套接字发送第一条消息,但之后没有任何消息
【发布时间】:2019-03-26 04:59:34
【问题描述】:

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

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

【问题讨论】:

  • 客户端只连接一次(OK),但服务器在每次while循环开始时等待传入连接。
  • 哦!我太笨了!多谢!我终于第一次让这个工作了。
  • @timgeb 请将此评论转化为答案。
  • @GottaAimHigherPal 还有什么不清楚的地方吗?

标签: python sockets general-network-error


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-04
    • 2012-12-13
    • 2015-05-17
    • 2012-03-25
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多