【问题标题】:Test TCP connection for Client & Server on local machine在本地机器上测试客户端和服务器的 TCP 连接
【发布时间】: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 谢谢。我使用了一个更新的代码示例(请查看我的编辑)。示例代码现在可以工作了

标签: python sockets flask tcp


【解决方案1】:

嗯,客户端脚本在发送数据后立即结束……这至少很危险!竞争条件可能导致连接在对等方正确接收到任何内容之前被破坏。稳健的方法是使用graceful shutdown 客户端:

...
s.send(MESSAGE.encode('utf-8'))
s.shutdown(socket.SHUT_WR)     # tell peer we have nothing more to send
while True:
    data = s.recv(256)
    if len(data) == 0:         # but keep on until peer closes or shutdowns its side
        break

之后,我可以测试您的服务器脚本是否可以正确接收和发送回消息:

<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> starting up on localhost port 5005
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> waiting for a connection
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> connection from ('127.0.0.1', 62511)
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> received "b'Hello, World!'"
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> sending data back to the client
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> received "b''"
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> no more data from ('127.0.0.1', 62511)
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> waiting for a connection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-12
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2015-11-19
    • 2022-01-16
    • 2021-11-06
    相关资源
    最近更新 更多