错误:未连接传输端点(Python套接字)

时间:2016-03-13 11:33:59

标签: python multithreading sockets chat

我试图使用Python中的套接字(带线程)创建一个简单的聊天应用程序。应用程序是简单的客户端必须线程一个发送数据和另一个接收。服务器必须有两个线程,一个接受客户端连接,另一个接收广播消息。但是在运行以下代码时,我收到了错误消息

  

传输端点未连接

enter image description here

任何人都可以告诉我为什么我会收到此错误

客户端

import socket, threading

def send():
    msg = raw_input('Me > ')
    cli_sock.send(msg)

def receive():
    data = cli_sock.recv(4096)
    print('> '+ str(data))

if __name__ == "__main__":   
    # socket
    cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # connect
    HOST = 'localhost'
    PORT = 5028
    cli_sock.connect((HOST, PORT))     
    print('Connected to remote host...')

    thread_send = threading.Thread(target = send)
    thread_send.start()

    thread_receive = threading.Thread(target = receive)
    thread_receive.start()

服务器

import socket, threading

def accept_client():
    while True:
        #accept    
        cli_sock, cli_add = ser_sock.accept()
        CONNECTION_LIST.append(cli_sock)
        print('Client (%s, %s) connected' % cli_add)

def broadcast_data():
    while True:
        data = ser_sock.recv(4096)
        for csock in CONNECTION_LIST:
            try:
                csock.send(data)
            except Exception as x:
                print(x.message)
                cli_sock.close()
                CONNECTION_LIST.remove(cli_sock)

if __name__ == "__main__":    
    CONNECTION_LIST = []

    # socket
    ser_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # bind
    HOST = 'localhost'
    PORT = 5028
    ser_sock.bind((HOST, PORT))

    # listen        
    ser_sock.listen(1)
    print('Chat server started on port : ' + str(PORT))

    thread_ac = threading.Thread(target = accept_client)
    thread_ac.start()

    thread_bd = threading.Thread(target = broadcast_data)
    thread_bd.start()

1 个答案:

答案 0 :(得分:3)

您未正确使用服务器套接字。您不能在服务器套接字上recv,而是在它们上accept连接; accept返回实际的连接套接字:

ser_sock.listen(1)
sock, addr = ser_sock.accept()

print('Got connection from {}'.format(addr))

# only this *connection* socket can receive!
data = sock.recv(4096)