【发布时间】:2021-09-18 01:46:12
【问题描述】:
我正在使用 TCP 在我的本地计算机上尝试一个简单的发送/接收器示例。目标是打开一个 TCP 服务器并发送一些数据。我的设置是 Pycharm IDE 上的 Python3.6。我已启用发送方和接收方脚本的并行运行。
这是服务器脚本:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 5005)
print(sys.stderr, 'starting up on %s port %s' % server_address)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print(sys.stderr, 'waiting for a connection')
connection, client_address = sock.accept()
try:
print(sys.stderr, 'connection from', client_address)
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print(sys.stderr, 'received "%s"' % data)
if data:
print(sys.stderr, 'sending data back to the client')
connection.sendall(data)
else:
print(sys.stderr, 'no more data from', client_address)
break
finally:
# Clean up the connection
connection.close()
这是客户端脚本:
import socket
TCP_IP = 'localhost'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE.encode('utf-8'))
我验证了这两个脚本都在运行,并且我已经使用调试器解析了发送方的每一行。我没有收到任何错误,但我也没有看到服务器收到任何内容。
编辑: 我用过example code from this page 服务器:
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
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 + b' from server')
客户:
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # 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))
我得到了预期的结果:
收到 b'Hello, world from server'
【问题讨论】:
-
什么都打印在服务器端?另外,对于您的打印,您的意思是
print('connection from', client_address, file=sys.stderr)打印到标准输出吗?您当前的代码只是打印对象本身。 -
@Carcigenicate 谢谢。我使用了一个更新的代码示例(请查看我的编辑)。示例代码现在可以工作了