聊天中的Python客户端 [英] Python client side in chat
本文介绍了聊天中的Python客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试建立聊天的客户端时遇到问题。我只是刚开始,这是我的代码:
I have a problem while trying to build the client side of a chat. I just in the begining, this is my code:
import socket
my_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
my_socket.connect(("10.10.10.69",1234))
while True:
message=raw_input("your message: ")
if(message=="quit"):
my_socket.close()
break
my_socket.send(message)
data=my_socket.recv(1024)
print "message from server:" , data
问题是 raw_input
。当一个用户发送一条消息时,其他用户堆叠在 raw_input
上,因此只有当他们也发送一条消息时,他们才能收到新消息。
The problem is the raw_input
. When a user sends a message the other users are stacked on the raw_input
so only when they sends a message too they get the new messages.
如何修复它(不使用线程)?
How can I fix it (without using threads)?
推荐答案
正如我评论的那样,使用 select.select
如果您的聊天客户端在Unix上运行。
As I commented, use select.select
if your chat client is running in Unix.
例如:
import socket
import sys
import select
my_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
my_socket.connect(("10.10.10.69",1234))
sys.stdout.write('your message: ')
sys.stdout.flush()
while True:
r, w, x = select.select([sys.stdin, my_socket], [], [])
if not r:
continue
if r[0] is sys.stdin:
message = raw_input()
if message == "quit":
my_socket.close()
break
my_socket.send(message)
sys.stdout.write('your message: ')
sys.stdout.flush()
else:
data = my_socket.recv(1024)
print "message from server:" , data
这篇关于聊天中的Python客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文