![](/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.