[英]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.