尝试在 python 中创建客户端和服务器来发送和接收一些东西
try to make a client and server in python to send and receive some thing
这是我创建服务器的代码:
from socket import *
s = socket(AF_INET , SOCK_STREAM)
s.bind(("",9090))
s.listen(1)
print("Server Binding on port 9090 ...\n")
client , addr = s.accept()
print ("Connected to" +str(addr)+'\n')
while True:
msg = input("Message = ")
msg2 =client.sendall(msg.encode("utf-8"))
msg2 = client.recv(1024)
msg2 = str(msg2)
print (msg2)
当我在 cmd 中 运行 直到我想从客户端向服务器发送消息时,我在客户端收到 'str' 错误:
服务器:
Server Binding on port 9090 ...
Connected to('192.168.43.16', 4642)
Message = salam
客户:
C:\Users\Administrator>python
Python 3.8.2(tags/v3.8.2:7b3ab59,2020 年 2 月 25 日,23:03:10)Win32 上的 [MSC v.1916 64 位 (AMD64)]
键入“帮助”、“版权”、“信用”或“许可”以获取更多信息。
>>> from socket import *
>>> s =socket(2,1)
>>> s.connect(("192.168.43.16",9090))
>>> s.recv(1024)
b'salam'
>>> s.send("salam")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
由于您要发送字节,因此您应该对要发送到服务器的消息进行编码。
你有 s.send("salam")
的地方应该是 s.send("salam".encode('utf-8'))
.
希望对您有所帮助。
这是我创建服务器的代码:
from socket import *
s = socket(AF_INET , SOCK_STREAM)
s.bind(("",9090))
s.listen(1)
print("Server Binding on port 9090 ...\n")
client , addr = s.accept()
print ("Connected to" +str(addr)+'\n')
while True:
msg = input("Message = ")
msg2 =client.sendall(msg.encode("utf-8"))
msg2 = client.recv(1024)
msg2 = str(msg2)
print (msg2)
当我在 cmd 中 运行 直到我想从客户端向服务器发送消息时,我在客户端收到 'str' 错误: 服务器:
Server Binding on port 9090 ...
Connected to('192.168.43.16', 4642)
Message = salam
客户:
C:\Users\Administrator>python
Python 3.8.2(tags/v3.8.2:7b3ab59,2020 年 2 月 25 日,23:03:10)Win32 上的 [MSC v.1916 64 位 (AMD64)] 键入“帮助”、“版权”、“信用”或“许可”以获取更多信息。
>>> from socket import *
>>> s =socket(2,1)
>>> s.connect(("192.168.43.16",9090))
>>> s.recv(1024)
b'salam'
>>> s.send("salam")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
由于您要发送字节,因此您应该对要发送到服务器的消息进行编码。
你有 s.send("salam")
的地方应该是 s.send("salam".encode('utf-8'))
.
希望对您有所帮助。