Python网络聊天

时间:2015-09-28 10:20:55

标签: python sockets networking

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

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

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

chatClient.py3

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

1 个答案:

答案 0 :(得分:0)

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

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

s.connect(server)