gpt4 book ai didi

sockets - 套接字编程Python

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

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 8021))
s.listen(10)

while True:
conn, addr = s.accept()
print 'got connected from', addr
s.send("sending to client")
conn.close()
s.close()

问题是我运行客户端代码后,它显示 "got connected from ('127.0.0.1', 52764)",但随后显示错误
Traceback (most recent call last):
File "D:\Python27\server", line 13, in <module>
s.send("sending to client")
error: [Errno 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

我该如何纠正?

我的客户代码是:
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = 'localhost'
port = 8021


s.connect((host, port))

revieved = s.recv(1024)
print "Recieved: ", recieved

最佳答案

好吧,答案很简单,我在这里可能会赢得一些声誉!

您正在将常规套接字与特定的客户端连接混淆。运行s.accept()会收到一个元组,该元组包括:远程套接字连接对象和远程套接字地址。这样,您可以通过引用正确的连接对象来与特定的客户端对话。

因此,固定内容可能如下所示:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 8021))
s.listen(10)

while True:
conn, addr = s.accept()
print 'got connected from', addr
conn.send("sending to client")
conn.close()
s.close()

假设其他一切都正常!

关于sockets - 套接字编程Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26513937/

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