![](/img/trans.png)
[英]Python 3 socket client sending data and C++ socket server receiving data with offset?
[英]Python Socket Programming: sending and receiving int data between server and client?
我正在编写一些代码,它使用 python 的socket
建立客户端和服务器。我想在我的客户端中获取用户输入,将该数据发送到我的服务器,然后让服务器将该信息发送回我的客户端并存储它作为一个int
这是我的服务器代码:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 8890))
s.listen(5)
while True:
s.listen()
conn, addr = s.accept()
print(f"Connection established from address {addr}")
choice = s.recv(2048)
conn.send(str(choice).encode('utf8'))
conn.close()
这是我的客户端代码:
import socket
choice = input("Select: ")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 8890))
s.send(str(choice).encode('utf8'))
msg = s.recv(2048)
strings = msg.decode('utf8')
num = int(strings)
目前,这段代码给我这个错误信息:
Traceback (most recent call last):
File "/Users/user/PycharmProjects/test/client.py", line 12, in <module>
msg = s.recv(2048)
ConnectionResetError: [Errno 54] Connection reset by peer
任何输入将不胜感激。
离工作很近了。 在服务器端choice = s.recv(2048)
应该是choice = conn.recv(2048)
。 另外s.listen()
和conn, addr = s.accept()
应该在循环之外。
#the server
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 8890))
s.listen()
conn, addr = s.accept()
with conn:
print(f"Connection established from address {addr}")
while True:
choice = conn.recv(2048)
if not choice:
break
conn.send(str(choice).encode('utf8'))
#the client
import socket
choice = input("Select: ")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 8890))
s.send(str(choice).encode('utf8'))
msg = s.recv(2048)
strings = msg.decode('utf8')
# not sure if best solution but it's a quick fix
cleaned_num = int(strings.strip("b\'"))
print(f"Number is: {cleaned_num} ")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.