【问题标题】:Unable to use sockets to send data over the internet in python无法使用套接字在 python 中通过 Internet 发送数据
【发布时间】:2021-01-25 04:44:40
【问题描述】:

我正在尝试编写一个脚本来使用套接字通过 Internet 传输图像(代码如下所示)。当我在本地机器上尝试时,代码工作正常,但是当我对连接到同一个 WiFi 网络的 2 台不同的计算机(1 台作为服务器,1 台作为客户端)执行相同操作时,它们甚至没有相互连接让单独传输数据。有人可以帮忙吗?

服务器代码:-

import socket
import base64
import sys
import pickle

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 8487))
s.listen(5)
while True:
    # After the Connection is established
    (clientsocket, address) = s.accept()
    print(f"Connection form {address} has been established!")
    # Initiate image conversion into a string
    with open("t.jpeg", "rb") as imageFile:
        string = base64.b64encode(imageFile.read())
        msg = pickle.dumps(string)
        print("Converted image to string")
        # Send the converted string via socket encoding it in utf-8 format
        clientsocket.send(msg)
        clientsocket.close()

        # Send a message that the string is sent
        print("String sent")
        sys.exit()

客户端代码:-

import socket, pickle, base64

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 8487))

while True:
    data = []
    # Recieve the message
    while True:
        packet = s.recv(1000000)
        if not packet:
            break
        data.append(packet)
        print("Message recieved")

    # Decode the recieved message using pickle
    print("Converting message to a String")
    string = pickle.loads(b"".join(data))
    print("Converted message to String")

    # Convert the recieved message to image
    imgdata = base64.b64decode(string)
    filename = 'tu.jpeg'
    with open(filename, 'wb') as f:
        f.write(imgdata)
    s.shutdown()
    s.close()

【问题讨论】:

  • 您是否检查过防火墙上相应的 TCP 端口是否打开?
  • 客户端需要连接到服务器的主机名,而不是自己的名字——所以socket.gethostname()是错误的!
  • 不需要 b64 或泡菜。只需clientsocket.sendall(imageFile.read())

标签: python sockets data-transfer data-transfer-objects


【解决方案1】:
 s.connect((socket.gethostname(), 8487))

您的客户端尝试连接到本地主机。如果服务器主机是本地主机,这是可行的。但是如果服务器主机不同,这当然不会连接到服务器。相反,您必须在此处提供服务器系统的 IP 地址或主机名。

【讨论】:

  • 我是套接字编程的新手。你能告诉我代码需要是什么
  • @GuneetSingh:我已经尽可能地做到了。引用我自己的话:“...在此处提供服务器系统的 IP 地址或主机名。”。当然,我不知道你的服务器有什么名字或IP地址,你需要自己弄清楚。
猜你喜欢
  • 1970-01-01
  • 2020-02-29
  • 2013-01-23
  • 2013-08-21
  • 1970-01-01
  • 2021-08-15
  • 1970-01-01
  • 2014-06-05
  • 2016-04-06
相关资源
最近更新 更多