简单的客户端 - 服务器应用程序。
#Server use decode
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host,port))
s.listen(5)
while True:
c,addr = s.accept()
print("Got connection from " + str(addr))
ret_val = s.send("Thank you".encode('utf-8'))
print ("ret_val={}".format(ret_val))
c.close()
客户端:
#client use decode
from socket import gethostname, socket
serSocket = socket()
server = gethostname()
port = 12345
serSocket.connect((server, port))
data = serSocket.recv(1024)
msg = data.decode('utf-8')
print("Returned Msg from server: <{}>".format(msg))
serSocket.close()
当服务器尝试发送以下异常时
Traceback (most recent call last):
Got connection from ('192.168.177.1', 49755)
File "C:/Users/Oren/PycharmProjects/CientServer/ServerSide/Server2.py", line 16, in <module>
ret_val = s.send("Thank you".encode('utf-8'))
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
Process finished with exit code 1
可以看出,客户端成功连接了服务器。 但发送失败。
有什么问题?
答案 0 :(得分:2)
问题是您正在发送监听套接字,而不是连接的套接字上。 connect
返回一个新套接字,这是您必须用于数据传输的套接字。监听套接字永远不能用于发送或接收数据。
将发送更改为此,您的程序将正常运行:
ret_val = c.send("Thank you".encode('utf-8'))
(注意c.send
,而不是s.send
)