通过套接字将消息从PHP发送到Python

2 投票
1 回答
6453 浏览
提问于 2025-04-18 08:21

我正在尝试用PHP给一个Python的socket发送消息,并希望它能打印出这条消息。

这是我目前写的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

看起来我真的很迷茫。

有人能帮帮我吗?

谢谢。

1 个回答

4

试试下面这个:

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?)。

撰写回答