Python socket编程

source: http://blog.sina.com.cn/s/blog_523491650100hikg.html

server端

import socket
if __name__ == '__main__':

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 8001))
    sock.listen(5)
while True:
    connection,address = sock.accept()
    try:
        connection.settimeout(5)
        buf = connection.recv(1024)
        if buf == '1':
            connection.send('welcome to server!')
        else:
            connection.send('please go out!')
    except socket.timeout:
        print 'time out'
    connection.close()

client端

import socket
import time
if __name__ == '__main__':

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('localhost', 8001))

    time.sleep(1)
    sock.send('1')
    print sock.recv(1024)
    sock.close()

在终端运行server.py,然后运行clien.py,会在终端打印“welcome to server!"。如果更改client.py的sock.send('1')为其它值在终端会打印”please go out!“ ,更改time.sleep(2)为大于5的数值, 服务器将会超时。


posted @ 2022-04-29 22:37  WORDLESS  阅读(29)  评论(0编辑  收藏  举报