[python&php 网络编程]把socket改成阻塞或非阻塞模式

1.python写法

import socket

def test_socket_modes():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setblocking(1)
    s.settimeout(0.5)
    s.bind(("127.0.0.1", 0))
    
    socket_address = s.getsockname()
    print "Trivial Server lauched on socket: %s" %str(socket_address)
    while(1):
        s.listen(1)
  
if __name__ == '__main__':
    test_socket_modes()

2.php写法

0.5, 'usec'=>0));
    socket_bind($socket, '127.0.0.1', '8686');
    printf("Trivial Server lauched on socket: (%s)\n", '127.0.0.1, 8686');
    while(1){
        socket_listen($socket);
    }
}

test_socket_modes();

代码量差不多,php我之间bind一个端口,在shell下lsof出端口可以查到

COMMAND   PID  USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
php     15249 baidu    3u  IPv4 0x22580e0c0af2b3a9      0t0  TCP localhost:sun-as-jmxrmi (LISTEN)
COMMAND   PID USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
Python  15263 root    3u  IPv4 0x22580e0c0b43c3a9      0t0  TCP localhost:56040 (LISTEN)

转载请标注原文地址:

你可能感兴趣的:(python,php)