Python 2.6聊天循环问题.不能同时接收和发送 [英] Python 2.6 Chat Loop Issue. Cant Receive And Send Simultaneously

查看:112
本文介绍了Python 2.6聊天循环问题.不能同时接收和发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个控制台聊天程序,但是我的循环有问题.我无法同时获得输入和其他人的输入.如果从一端发送了两条或更多条消息,则另一端直到发送完一条消息后,才能接收下一条消息.我对python相当陌生,并一直在寻找正确的方向.我已经想到了多线程,但是那一点超出了我的掌握范围.还有其他想法吗?

Im trying to make a console chat program, but have a problem with my loop. I cant get input and receive the other persons input at the same time. If two message or more are sent from one end, the other end cant receive the next message until after it sends one. Im fairly new to python, and was looking for a nudge in the right direction. Ive thought of multi-threading, but thats a little outta my grasp atm. Any other ideas?

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()

推荐答案

线程并没有您想象的那么难,并且精通线程是对工具的宝贵补充.

Threading isn't as hard as you think, and mastering it is an invaluable addition to your toolchest.

只需创建一个类作为Thread的子类,并确保它具有run()方法.然后实例化该类并调用其start()方法.

Just make a class that is a subclass of Thread and make sure it has a run() method. then instantiate the class and call its start() method.

使线程停止更难正确地进行.最好设置一个标志,并确保您在while循环中定期检查它,因此您需要在阻塞的recv()上设置一个超时,例如1秒.

Making the thread stop is more difficult to do right. Best to set a flag and make sure you check it regularly in your while loop, hence you need a timeout on your blocking recv(), of, say, 1 second.

from socket import *
from threading import Thread


#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'


class ReceiveThread(Thread):

    def __init__(self, sock):
        Thread.__init__(self)
        self.sock = sock
        self.shouldstop = False

    def run(self):
        self.sock.settimeout(1)
        while not self.shouldstop:
            try:
                data = self.sock.read()
                print data
            except socket.timeout:
                continue

    def stop(self):
        self.shouldstop = True


# start receive loop:
r = ReceiveThread(EncCon).start()


#Send Loop
while 1:
    MsgOut = raw_input()
    if MsgOut: EncCon.send(MsgOut)

    if MsgOut == '.':
        r.stop()
        r.join()


EncCon.close()

现在,此程序仍然存在原始问题,因为您不收听而是立即连接,因此无法启动两个实例.但是,我认为那不是您问题的主要内容.

Now, this program still has the original problem that it would be impossible to start two instances, as you do not listen, but immediately connect. But that, I believe, was not the main part of your question.

这篇关于Python 2.6聊天循环问题.不能同时接收和发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆