Python 网络聊天 [英] Python Networked Chat

查看:51
本文介绍了Python 网络聊天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照教程进行网络聊天.我有两个模块,chatServer.py3 和 chatClient.py3.在启动服务器,然后是客户端并尝试发送消息时,我收到以下错误:

I was working on a networked chat by following a tutorial. I have two modules, chatServer.py3 and chatClient.py3. On starting the server and then a client and attempting to send a message I get the following error:

Traceback (most recent call last): File "chatClient.py3", line 49, 
in <module> 
Main() File "chatClient.py3", line 38, in Main 
s.sendto(alias+": "+message, server) 
socket.error: [Errno 57] Socket is not connected

请记住,我是一个新手,因此如果解决方案及其解释过于简单,我将不胜感激.

Please keep in mind that I am a rookie and therefore I would appreciate if the solutions along with their explanations were simplistic.

import socket, time, threading
tLock = threading.Lock()
shutdown = False

def recieveing(name,sock):
    locked = False
    while not shutdown:
        try:
            tLock.aquire()
                  locked = True
        while True:
            data , addr = sock.recv(1024)
            print str(data)
        except:
            pass
        finally:        
            if locked:  
                tLock.release()


def Main():
    host = '127.0.0.1'
    port = 0
    server = ('127.0.0.1', 5000)
    s = socket.socket()
    s.bind((host,port))
    s.setblocking(0)

    rT = threading.Thread(target=recieveing,args=("RecivedThread",s))
    rT.start()

    alias = raw_input("Name: ")
    message = raw_input(alias+"-> ")

    while message != "q":
        if message != "":
            s.sendto(alias+": "+message, server)
        tLock.aquire()
        message = raw_input(alias+"-> ")
       tLock.release()
        time.sleep(0.2)

    shutdown = True
    rT.join()
    s.close()

if __name__ == '__main__':
    Main()

chatServer.py3

import socket,time

host = '127.0.0.1'
port = 5000
clients = []


s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host,port))
s.setblocking(0)

quitting = False
print "Server Started."

while not quitting:
    try:
        data, addr = s.recvfrom(1024)
        if "Quit" in str(data):
            quitting = True
        if addr not in clients:
            clients.append(addr)
        print time.ctime(time.time()) + str(addr) + " : : "+str(data)

        for client in clients:
            s.sendto(data, client)
        except:
            pass


s.close()

推荐答案

您不需要将您的客户端绑定到主机和端口.bind 命令定义了服务器需要监听的位置.客户端需要连接到服务器.像这样:

You don't need to bind your client to the host and port. The bind command defines where the server needs to listen. The client needs to connect to the server. Like this:

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server = ('127.0.0.1', 5000)

s.connect(server)

这篇关于Python 网络聊天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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