PHP / Python套接字远程连接问题

时间:2018-02-08 15:58:36

标签: php python sockets

我有这个python代码:

from socket import *
import threading
import thread
import time
import json

def handler(clientsock,addr):
    while 1:
        time.sleep(2)
        data = clientsock.recv(65535);
        if not data:
            break
        object = json.loads(data)
        object['status'] = 1
        object['timestamp'] = time.time()
        output = json.dumps(object)        
        msg = output
        clientsock.send(msg)
    clientsock.close()

if __name__ == '__main__':
    HOST = '192.168.0.28'
    PORT = 5555
    BUFSIZ = 65535
    ADDR = (HOST, PORT)

    serversock = socket(AF_INET, SOCK_STREAM)
    serversock.bind(ADDR)
    serversock.listen(5)

    while 1:
        print 'waiting for connection...'
        clientsock, addr = serversock.accept()
        print '...connected from: ', addr
        thread.start_new_thread(handler, (clientsock, addr))

和这个PHP代码:

<?php 
/**
 *
 * PHP JSON Echo Server client
 *
*/
// python server socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, '192.168.0.28', 5555);
//Create a message, and send it to the server on $socket.
$data = array(
    'username' => 'sysadmin',
    'key' => '093ufj408xr0289u3r0x9u2m309x',
    'action' => 'login',
);
$json = json_encode($data);
socket_send($socket, $json, strlen($json), MSG_EOF);
$data = socket_read($socket, 65535);
$object = json_decode($data);
if($object->status) {
    echo '<p>Data received successfully.';
} else {
    echo '<p>Error. Data not read correctly!';
}
echo '<p>'.$data;
//Close the socket.
socket_close($socket);
?>

如果我在本地网络中运行它,它可以正常运行。但是当我在外部托管上执行PHP脚本时,它不再起作用了。我已经将IP地址更改为我的WAN IP地址,甚至更改为ISP提供的DNS。什么都行不通。

这是输出:

Warning: socket_connect(): unable to connect [111]: Connection refused in /home/usr/public_html/webclient.php on line 9

Warning: socket_send(): unable to write to socket [32]: Broken pipe in /home/usr/public_html/webclient.php on line 17

Warning: socket_read(): unable to read from socket [107]: Transport endpoint is not connected in /home/usr/public_html/webclient.php on line 18
Error. Data not read correctly!

我尝试使用此服务扫描开放端口:http://www.ipfingerprints.com/portscan.php并且端口5555已打开。我也从服务器收到了一条消息:

waiting for connection...
...connected from:  ('5.79.68.210', 36080)

问题出在哪里?

1 个答案:

答案 0 :(得分:0)

关于此代码:

print '...connected from: ', addr

您无法使用此代码,因为知道开放端口您需要使用此代码:

print '...connect from: ' + addr[0] + ':' + str(addr[1])

只有那个

你并且直接使用套接字:

serversock = socket(AF_INET, SOCK_STREAM)

使用它会更好:

serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)