C/S模式简介
Tcp通信模型
Udp通信模型
python标准库中的socket模块
用socket建立TCP服务器端
用socket建立UDP服务器端
socket TCP服务器端测试代码
#coding:utf-8 import socket#Host=''表示为本机地址 HOST='' PORT=3214#默认为IPV4,TCP协议 s=socket.socket() s.bind((HOST,PORT))s.listen(5)clnt,addr=s.accept()print "Client Address:",addrwhile True:data=clnt.recv(1024)if not data:break#把二进制解码为utf-8print 'receive data:',data.decode('utf-8')clnt.send(data) clnt.close() s.close()
socket UDP服务器端测试代码
#coding:utf-8 import socket#ip:127.0.0.1,port 3214 HOST='' #warning:Ip addr can only be dropped in server! PORT=3214#AF_INET IPV4 #SOCK_DGRAM UDP s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind((HOST,PORT))data=True while data:data,addr=s.recvfrom(1024)if data == b'bye':breakprint 'Receive String:',data.decode('utf-8')s.sendto(data,addr) s.close()