【问题标题】:How to send data from client socket to server socket using Python?如何使用 Python 将数据从客户端套接字发送到服务器套接字?
【发布时间】:2020-06-01 12:13:02
【问题描述】:

运行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'"

我的问题是:

  1. 为什么服务器打印的是服务器 ip 而不是客户端 ip?如果我指定了端口,为什么端口是随机的?

  2. 如果我的服务器套接字正在运行,如何将数据从连接的客户端套接字发送到服务器套接字?

例如:x = 'random string'。客户端套接字连接后,如何发送'x' 以便在服务器端接收?

【问题讨论】:

    标签: python sockets


    【解决方案1】:
    1. 电脑总是使用随机端口连接,这是正常的。关于为什么打印服务器IP,你错了,没有理由打印服务器IP,服务器IP是127.0.0.1。我想你已经在同一台机器上运行了服务器和客户端。

    2. 让我告诉你你做了什么:

    3. 服务器 客户端
    4. 服务器 ---------------------------------- 客户端

      |\________________

      |有联系!|

    5. 服务器
    6. 服务器-----------你好世界---------->客户端
    7. 服务器 ---------------------------------- 客户端

                            _____________________/|
      
                           |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
    

    【讨论】:

    • 谢谢你的回答,我的问题不是如何从服务器发送到客户端,而是如何从客户端发送到服务器。
    • 您已经在您的客户端代码中将数据从客户端发送到服务器:s.sendall(b'Hello, world')
    • 数据“b'Hello, world'”打印在客户端而不是服务器上。
    • 抱歉,我没有看到您编辑了您的评论。谢谢
    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 2015-10-25
    • 1970-01-01
    相关资源
    最近更新 更多