显示输出的raw_input而内部()(Display output while inside of

2019-10-19 12:01发布

我实现一个聊天服务器,而我现在有我想通过发送信息客户端套接字的列表,问题是,客户端在的raw_input()状态存在以发送邮件通过服务器中继,和每个客户端的缓冲器被填充,直到该客户端本身进入东西在的raw_input()字段,在该点它打印它的接收缓冲器为单行块。

我想每一个客户得到的东西在他们的缓冲立即显示,即使它们的raw_input卡内()。

这里是我的输出:

cli1.py

Your Message: test
Your Message: Received  "'test'"
test
Received  "'test'"
Your Message: 

cli2.py

Your Message: test
Your Message: Received  "'test'"
1
Received  "'test''test'"
Your Message: 

server.py

Server is running......
('127.0.0.1', 58919) is Connected
('127.0.0.1', 58920) is Connected
Received Message 'test'
we have connected:  <socket._socketobject object at 0x1004b6f30>
we have connected:  <socket._socketobject object at 0x1004e98a0>
Received Message 'test'
we have connected:  <socket._socketobject object at 0x1004b6f30>
we have connected:  <socket._socketobject object at 0x1004e98a0>
Received Message 'test'
we have connected:  <socket._socketobject object at 0x1004b6f30>
we have connected:  <socket._socketobject object at 0x1004e98a0>
Received Message '1'
we have connected:  <socket._socketobject object at 0x1004b6f30>
we have connected:  <socket._socketobject object at 0x1004e98a0>

和我的实际代码:

CLI1 = CLI2:

from socket import *
from threading import Thread
import sys

def iamclient():
    message = raw_input("Your Message: ")
    s.send(message)
    reply = s.recv(1024) # 1024 is max data that can be received
    print "Received ", repr(reply)

HOST = ''
PORT = 8003

s = socket(AF_INET, SOCK_STREAM)
try:
    s.connect((HOST, PORT)) # client-side, connects to a host
except:
    print 'Max capacity reached, try again later'
    s.close()
    sys.exit()


Thread(target=iamclient).start()
while True:
    iamclient()

s.close()

server.py

from socket import *
from threading import Thread

def clientHandler():
    conn, addr = s.accept()
    connlist.append(conn)
    print addr, "is Connected"
    while 1:
        data = conn.recv(1024)
        if not data:
            break
        print "Received Message", repr(data)
        for i in connlist:
            print "we have connected: ",i
            i.send(repr(data))


HOST = '' #localhost
PORT = 8003

s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(2)

connlist = []

print "Server is running......"

#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()

for i in range(2):
    Thread(target=clientHandler).start()

s.close()

Answer 1:

由于(如@thefourtheye说的) raw_input是在主线程中的I / O块,所以你需要创建一个单独的线程来打印信息。

多线程的解决方案:

>>> def print_message():
    time.sleep(5)
    print "message"


>>> bgThread = Thread(target=print_message)
>>> bgThread.start()
>>> x = raw_input()
message
input is entered here
>>> print x
input is entered here

使用一个单独的Thread接收和打印消息。



文章来源: Display output while inside of raw_input()