python 使用socket搭建简单服务器

来源:互联网 发布:数码宝贝网络侦探bgm 编辑:程序博客网 时间:2024/05/16 11:58

利用socket搭建简单服务器进行数据收发

下面是python语言用socket搭建服务器的收发程序代码(TCP):

server:

import socketsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  sock.bind(('192.168.3.10', 9401))  sock.listen(5)while True:      connection,address = sock.accept()      try:          connection.settimeout(5)          buf = connection.recv(1024)        print('address:', buf)    except socket.timeout:          print 'time out'      connection.close()  

client:

import socketimport time while True:    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)      sock.connect(('localhost', 8001))    time.sleep(2)    sock.send('1')    print sock.recv(1024)    sock.close()  
如有问题,请留言!
0 0