套接字未连接Python

时间:2018-08-13 12:46:54

标签: python python-3.x sockets

我尝试查看此问题,但没有帮助:Python Server Client WinError 10057

我的代码是这样:

import socket

def actual_work():

    return 'dummy_reply'


def main():
    sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    try:
        sock.bind( ('127.0.0.1', 6666) )

        while True:
            data, addr = sock.recvfrom( 4096 )
            reply = actual_work()
            sock.sendto(reply, addr)
    except KeyboardInterrupt:
        pass
    finally:
        sock.close()
if __name__ == '__main__':
    main()

收到以下错误:

Traceback (most recent call last):
  File "testserver.py", line 22, in <module>
    main()
  File "testserver.py", line 14, in main
    data, addr = sock.recvfrom( 4096 )
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

1 个答案:

答案 0 :(得分:1)

首先,您需要客户端代码才能与服务器连接。 这是一个TCP套接字,因此是面向连接的。

这意味着在进行任何数据传输(socket.recv(),socket.send())之前,您需要请求从客户端到服务器的连接,并且服务器必须接受该连接。

建立连接后,您将可以在套接字之间自由发送数据。

这是这种简单的套接字设计的示例,可以通用地应用于您的程序:

客户示例

import socket


# create an ipv4 (AF_INET) socket object using the tcp protocol (SOCK_STREAM)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# connect the client
# client.connect((target, port))
client.connect(('0.0.0.0', 9999))

# send some data (in this case a String)
client.send('test data')

# receive the response data (4096 is recommended buffer size)
response = client.recv(4096)

print(response)

服务器示例

import socket
import threading

bind_ip = '0.0.0.0'
bind_port = 9999
max_connections = 5 #edit this to whatever number of connections you need

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(max_connections)  # max backlog of connections

print (('Listening on {}:{}').format(bind_ip, bind_port))


def handle_client_connection(client_socket):
    request = client_socket.recv(4096 )
    print (str(request))
    client_socket.send('ACK!')
    client_socket.close()

while True:
    client_sock, address = server.accept()
    print (('Accepted connection from {}:{}').format(address[0], address[1]))
    client_handler = threading.Thread(
        target=handle_client_connection,
        args=(client_sock,)  # without comma you'd get a... TypeError: handle_client_connection() argument after * must be a sequence, not _socketobject
    )
    client_handler.start()

此示例应在服务器控制台和ACK中打印测试数据!在客户端控制台中。

edit:不确定python3打印的工作方式,因为我在这里写过...但这只是一个小细节。通常的想法是在这种情况下重要。当我上电脑时,如果出现语法错误,我将尝试运行此命令并更正打印内容