套接字编程端口帮助python

时间:2016-04-12 14:16:09

标签: python sockets

我正在尝试实现套接字编程,并希望将服务器和客户端的通信端口号配置为特定端口。我在客户端和服务器端都指定了相同的端口号,但是当程序运行时它还需要一个随机端口号。如何修复端口号/使其静止?

服务器端代码

<?php
$response = [];
if ( isset($_POST['service']) ) {
    // do your stuff; DO NOT output (echo) anything here, this is simply logic
    // ... do some more stuff

    // if everything has satisfied, send response back
    $response['success'] = true;

    // else, if this logic fails, send that response back
    $response['success'] = false;
}
else {
    // initial condition failed
    $response['success'] = false;
}
echo json_encode($response);

客户端代码

import socket
s=socket.socket()
port=12345
s.bind(("192.168.0.111",port))
s.listen(5)
while True:
    c, addr = s.accept()
    print("got connection from ",addr)
    sendingMessage = "Thank you for connecting"
    c.send(bytes(sendingMessage, 'UTF-8'))
    data = c.recv(16)
    receivedData=data.decode("utf-8","ignore")
    print (receivedData)
    c.close()
    if receivedData=="stop":
        break

1 个答案:

答案 0 :(得分:1)

如果您希望客户端也使用端口12345,则还必须绑定客户端端口号。 s.connect中给出的端口号是您要连接的远程端口。 IOW,您的代码应该在客户端看起来像这样:

s = socket.socket()
s.bind(('', port))
s.connect(("192.168.43.111", port))

您还可以在绑定中指定IP地址,但通常不需要,因为到远程主机的路由将建立本地IP地址。