【问题标题】:Sending a message from PHP to Python through a socket通过套接字从 PHP 向 Python 发送消息
【发布时间】:2014-07-23 05:37:35
【问题描述】:

我正在尝试使用 PHP 向 Python 套接字发送消息并打印消息。

这是目前为止的 PHP 代码:

<?
$host = "localhost";
$port = 12345;

$f = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($f, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 500000));
$s = socket_connect($f, $host, $port);

$msg = "message";
$len = strlen($msg);

socket_sendto($f, $msg, $len, 0, $host, $port);

socket_close($f);
?>

这里是 Python 的:

#!/usr/bin/python
# encoding: utf-8

import socket

s = socket.socket()
host = "localhost"
port = 12345
s.bind((host, port))

s.listen(5)
while True:
   c, addr = s.accept()
   print s.recv(1024)
   c.close()

但我收到以下错误:

Traceback (most recent call last):
  File "server.py", line 15, in <module>
    print s.recv(1024)
socket.error: [Errno 107] Transport endpoint is not connected

我也尝试过socket_​sendmsgsocket_​writefwrite 等等,但 Python 中的错误总是一样的,socket.error: [Errno 107] Transport endpoint is not connected

看来我真的迷路了。

谁能帮帮我?

谢谢。

【问题讨论】:

  • 我对套接字不太熟悉,但问题可能是你用 c.close() 关闭它,这样循环通过一次后它就不能再听它了吗?
  • @James 我删除了它,但我仍然收到错误消息。无论如何感谢您的帮助!
  • 如果它不能修复错误,您可能希望将其保留在那里。 (对不起,我在这里一点帮助都没有!)
  • @James 没问题,感谢您的宝贵时间。

标签: php python sockets


【解决方案1】:

尝试以下方法:

import socket

s = socket.socket()
host = "localhost"
port = 12345
s.bind((host, port))

s.listen(5)
while True:
   c, addr = s.accept()
   data = c.recv(1024)
   if data: print data
   c.close()

主要问题是您的代码调用了s.recv(),而它本应在c.recv() 上。还要确保在打印前检查收到的数据(是None?)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2017-08-05
    相关资源
    最近更新 更多