python中socket操作

python中socket操作

这里有比较详细的介绍:
http://blog.chinaunix.net/u2/84280/showart_1800132.html

把例子放这便于学习

服务端:

if __name__ == '__main__':
    import socket
    mysocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    mysocket.bind(('localhost',8008))
    mysocket.listen(5)
    while True:
        connection,address = mysocket.accept()
        try:
            connection.settimeout(5)
            buf = connection.recv(1024)
            if buf == '1':#接收到的如果为1就走这一步了!
                connection.send('welcome to server')
            else:
                connection.send('please go out')
        except socket.timeout:
            print 'time out'
        connection.close()

客户端:

if __name__ == '__main__':
    import socket
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.connect(('localhost',8008))
    import time
    time.sleep(2)
    sock.send('1')
    print sock.recv(1024)
    sock.close()

你可能感兴趣的:(python中socket操作)