我正在编写一个服务器代码来监听来自套接字的信息,但是当我按下字母时,PI 必须向客户端发送一条“消息”。这是我到目前为止所做的:
import select
import Queue
import socket
import time
import sys
import msvcrt
from msvcrt import getch
n = 0
HOST = ''
PORT = 2323
servsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
servsock.bind((HOST, PORT))
servsock.listen(5)
servsock.setblocking(0)
inputs = [servsock]
outputs = []
message_queues = {}
while 1:
(sread, swrite, serr) = select.select(inputs, outputs, []);
for sock in sread:
if sock is servsock:
(newsock, address) = servsock.accept()
newsock.setblocking(0)
print "New connection: ", address
inputs.append(newsock)
newsock.send("You are connected")
outputs.append(newsock)
else:
recv_msg = sock.recv(100)
if recv_msg == "":
(host, port) = sock.getpeername()
print "Client %s:%s disconnected" % (host,port)
sock.close()
inputs.remove(sock)
outputs.remove(sock)
else:
(host, port) = sock.getpeername()
print "Client %s:%s sent: %s "% (host,port,recv_msg)
for sock in swrite:
while msvcrt.kbhit():
if msvcrt.getch() == "p":
sock.send("Message")
但是看起来 select 到达了 swrite,进入了那里,但是它不再在 sread 和 swrite 之间迭代。如果我随时按“1”,它确实会向套接字发送“消息”,但它永远不会返回到 sread!我只需要一直阅读传入的消息,当我按下 P 键发送“消息”时,不会阻塞程序的其余部分。
你能帮我么?谢谢