gpt4 book ai didi

python - 套接字未连接Python

转载 作者:行者123 更新时间:2023-12-01 09:09:00 25 4
gpt4 key购买 nike

我尝试查看这个问题但没有帮助: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

最佳答案

首先,您需要一个客户端代码来连接您的服务器。这是一个 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()

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

编辑:不确定 python3 打印是否正常工作,因为我在这里写了它们......但这只是一个小细节。在这种情况下,总体思路才是重要的。当我到达电脑时,我会尝试运行它并纠正打印(如果有任何语法错误)

关于python - 套接字未连接Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51822735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com