我试图制作一个控制台聊天程序,但是我的循环有问题.我无法同时获得输入和其他人的输入.如果从一端发送了两条或更多条消息,则另一端在发送一条消息之前不能接收下一条消息.我对python相当陌生,并一直在寻找正确的方向.我已经想到了多线程,但是那一点超出了我的掌握.还有其他想法吗?
import EncMod
from socket import *
#Get User Info
Ip = raw_input('IP>>>')
Port = int(raw_input('Port>>>'))
User = raw_input('Username>>>')
#Open Socket To Server
EncCon = socket(AF_INET, SOCK_STREAM)
EncCon.connect((Ip, Port))
print '\nStarting Chat....'
print '\n<-------------------------------------------->\n\n'
#Send/Receive Loop
while 1:
MsgOut = raw_input()
if MsgOut: EncCon.send(MsgOut)
MsgIn = EncCon.recv(1024)
if MsgIn: print MsgIn
EncCon.close()
解决方法:
Twisted framework可用于帮助完成此任务.下面的代码将启动一个聊天服务器,然后客户端可以根据服务器实例设置连接到该聊天服务器并进行来回通信.您可以进行适当的修改以满足您的要求:
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
class Chat(LineReceiver):
def __init__(self, users):
self.users = users
self.name = None
self.state = "GETNAME"
def connectionMade(self):
self.sendLine("What's your name?")
def connectionLost(self, reason):
if self.users.has_key(self.name):
del self.users[self.name]
def lineReceived(self, line):
if self.state == "GETNAME":
self.handle_GETNAME(line)
else:
self.handle_CHAT(line)
def handle_GETNAME(self, name):
if self.users.has_key(name):
self.sendLine("Name taken, please choose another.")
return
self.sendLine("Welcome, %s!" % (name,))
self.name = name
self.users[name] = self
self.state = "CHAT"
def handle_CHAT(self, message):
message = "<%s> %s" % (self.name, message)
for name, protocol in self.users.iteritems():
if ':' in message:
self.exc(message.split(':')[0])
if protocol != self:
protocol.sendLine(message)
def exc(self, cmd):
print cmd
if cmd == 'who':
for i in self.users:
print i
class ChatFactory(Factory):
def __init__(self):
self.users = {} # maps user names to Chat instances
def buildProtocol(self, addr):
return Chat(self.users)
reactor.listenTCP(8123, ChatFactory())
reactor.run()