[英]How to send data from client socket to server socket using Python?
主機運行python3.8.0
第二台機器python 3.7.5
我在我的主機上創建了一個服務器套接字:
import socket
HOST = ''
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
我還在第二台機器上創建了一個客戶端套接字:
import socket
HOST = '' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
我的理解是,如果我運行server
套接字,然后通過運行client
套接字進行連接,我的服務器套接字應該打印: "connected by [client ip], [specified port]"
同時客戶端應該打印: "Received b'Hello, world'
。
發生的事情是我的服務器打印"connected by [server ip], [random port]"
並且客戶端打印"Received b'Hello, world'"
。
我的問題是:
為什么服務器打印服務器ip而不是客戶端ip? 如果我指定了端口,為什么端口是隨機的?
如果我的服務器套接字正在運行,我如何將數據從連接的客戶端套接字發送到服務器套接字?
例如: x = 'random string'
。 客戶端套接字連接后,如何發送'x'
以便在服務器端接收它?
電腦只是一直使用隨機端口連接,這是正常的。 關於為什么打印服務器IP,你錯了,沒有理由打印服務器IP,服務器IP是127.0.0.1。 我認為您在同一台機器上同時運行了服務器和客戶端。
讓我為您提供您所做的工作:
服務器 --------------------------------- 客戶端
|\\________________
|有聯系!|
服務器 --------------------------------- 客戶端
_____________________/| |Received 'Hello world'|
這就是為什么您的客戶端打印“Hello world”而不是服務器的原因。 看這個:
服務器
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024) # The server has received 'Hello world'
if not data:
break
conn.sendall(data) # The server has sent back 'Hello world'
客戶:
s.connect((HOST, PORT)) # Connected
s.sendall(b'Hello, world') # Send 'Hello world'
data = s.recv(1024) # The server has received it but sent back so now the client received again
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.