gpt4 book ai didi

Python 2.6 聊天循环问题。不能同时接收和发送

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:38:40 25 4
gpt4 key购买 nike

我试图制作一个控制台聊天程序,但我的循环有问题。我无法同时获得输入和接收其他人的输入。如果一端发送了两条或更多消息,则另一端必须发送一条消息才能收到下一条消息。我是 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()

关于Python 2.6 聊天循环问题。不能同时接收和发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11353419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com