【问题标题】:How to recieve data from a one socket and send it to another socket in python?如何从一个套接字接收数据并将其发送到python中的另一个套接字?
【发布时间】:2020-01-16 01:07:25
【问题描述】:

我对 Python 和编程有点陌生。所以如果我要问的是愚蠢的,请原谅我。所以我有这个应用程序通过服务器的端口 5555 连接到服务器。所以我重新配置了应用程序以连接到我的本地主机的 5555 端口,而不是实际的服务器。然后我写了一个python程序来监听127.0.0.1:5555并将所有数据发送到实际的服务器。这是程序

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind(("localhost", 5555))
    s.listen()
    conn, addr = s.accept()
    with conn:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s2:
            s2.connect(("actualserver",5555))
            while True:
                data = conn.recv(4096)
                if data:
                    print('Sent to the Server :', data)
                    s2.sendall(data)
                data1 = s2.recv(4096)
                if data1:
                    print('Received from the Server :', data1)
                    conn.sendall(data1)

所以问题是应用程序尝试连接到服务器并给我错误消息“服务器没有响应!”。 这个程序给出这样的输出

Sent to the Server : /x87 /x65 blah blah blah
Sent to the Server : /x87 /x65 blah blah blah
Sent to the Server : /x87 /x65 blah blah blah
And an error, saying connection disconnected by an application of your host

我不明白问题出在哪里。请帮忙。

【问题讨论】:

  • 你能分享确切的错误堆栈跟踪吗?你知道服务器对你发送给它的数据做了什么吗?
  • 如果数据在一个方向发送,但在另一个方向没有任何内容,您的程序将等待后者,直到超时才会处理前者。
  • @OferSadan 当然,这里是Traceback (most recent call last): File "C:\Personal\Projects\test.py", line 16, in <module> data = conn.recv(4096) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
  • @MichaelButscher 我正在双向发送数据。我使用s2.sendall(data)将来自应用程序的数据发送到服务器,并使用conn.sendall(data1)将来自服务器的数据发送到应用程序
  • 如果 e. G。只有应用程序发送数据而服务器不发送数据,您的程序可能会等待来自服务器的一些数据,而来自应用程序的数据直到超时才会处理。

标签: python sockets


【解决方案1】:

在 127.0.0.1 或其他 ip 上更改 localhostactualserver,打开 5555 端口。

【讨论】:

  • 所提供的答案被标记为低质量帖子以供审核。以下是How do I write a good answer? 的一些指南。这个提供的答案可能是正确的,但它可以从解释中受益。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-08
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
  • 2016-04-28
  • 1970-01-01
相关资源
最近更新 更多