Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
错误:未连接传输终结点(Python套接字)_Python_Multithreading_Sockets_Chat - Fatal编程技术网

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

错误:未连接传输终结点(Python套接字),python,multithreading,sockets,chat,Python,Multithreading,Sockets,Chat,我正在尝试使用Python中的套接字(带有线程)创建一个简单的聊天应用程序。应用程序很简单,客户端必须执行一个线程来发送数据,另一个线程来接收数据。服务器必须有两个线程,一个接受客户端连接,另一个广播消息。但是在运行下面的代码时,我收到了错误消息 传输终结点未连接 有人能告诉我为什么我会犯这个错误吗 客户 import socket, threading def send(): msg = raw_input('Me > ') cli_sock.send(msg) d

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

传输终结点未连接

有人能告诉我为什么我会犯这个错误吗

客户

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

您使用的服务器套接字不正确。您不能在服务器套接字上
recv
,而是在它们上创建连接
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)