在本地机器上测试客户端和服务器的 TCP 连接

时间:2021-07-07 13:47:35

标签: python sockets flask tcp

我正在使用 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'

1 个答案:

答案 0 :(得分:0)

嗯,客户端脚本在发送数据后立即结束......这至少是危险的!竞争条件可能导致在对等方正确接收任何内容之前破坏连接。可靠的方法是使用 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