Python socket编程

来源:互联网 发布:免费手机短信群发软件 编辑:程序博客网 时间:2024/05/16 08:25

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

server端

import socketif __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 socketimport timeif __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的数值, 服务器将会超时。


原创粉丝点击