更新时间:2023-02-13 19:55:48
我在服务器中成功!
我的服务器python脚本如下:
My server python script is below:
import socket
host='0.0.0.0'
port=2345
s=socket.socket()
s.bind((host,port))
s.listen(2)
while True:
conn,addr=s.accept()
print("Connected by",addr)
data=conn.recv(1024)
print("received data:",data)
conn.send(data)
conn.close()
我的客户端python脚本如下:
My Client python script is below:
import socket
s=socket.socket()
host="xx.xx.xx.xx" #This is your Server IP!
port=2345
s.connect((host,port))
s.send(b"hello")
rece=s.recv(1024)
print("Received",rece)
s.close()
脚本中有两点需要注意:
There is two points needed to be careful in the script:
1.服务器的主机必须为
1.The host of the Server must is
'0.0.0.0'
'0.0.0.0'
以便python脚本可以使用服务器中的所有接口
So that the python script could user all interfaces in the server
2.我已经通过提示符找到问题的错误:
2.I have find the question's error through the prompt:
TypeError:需要一个类似字节的对象,而不是'str'
TypeError: a bytes-like object is required, not 'str'
这意味着'send'方法中的每个字符串消息都需要转换为'bytes-like object',所以正确的是
It means every string message in the 'send' method need to convert to 'bytes-like object',So the correct is
s.send(b"hello")
s.send(b"hello")
重要的是,这是 b'hello'
,而不是'hello'
It is important that this is b'hello'
not is 'hello'