点对点通讯分为客户端和服务器,多个客户端通过服务器进行信息的交流
服务器端代码 service端
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import SocketServer 5 import subprocess 6 7 ## 代号 地址和端口 连接对象 8 class myconn(object): ##存放连接 9 listconn = {} ## 地址端口 连接对象 10 # codeflage = {} ## 代号 地址端号 11 12 13 class MyServer(SocketServer.BaseRequestHandler): 14 15 def setup(self): 16 myconn.listconn[self.client_address] = self.request 17 pass 18 19 def handle(self): 20 print("got connection from",self.client_address) 21 while True: 22 conn = self.request 23 data = conn.recv(1024) 24 if not data: 25 break 26 print data 27 28 #如果目标客户端在发送数据给目标客服端 29 # 这里可以根据对方的ip和端口号来查找 我这里直接发给每一个用户了 30 print len(myconn.listconn) 31 if len(myconn.listconn) > 1: 32 for i in myconn.listconn.keys(): 33 if self.client_address != i: 34 myconn.listconn[i].sendall(data) 35 pass 36 else: ##不再 则发送数据给客户端 37 conn.sendall(data) 38 pass 39 conn.sendall(data) 40 41 def finish(self): 42 del myconn.listconn[self.client_address] 43 pass 44 pass 45 46 if __name__ == '__main__': 47 server = SocketServer.ThreadingTCPServer(('localhost',8022),MyServer) 48 print 'waiting for connection...' 49 server.serve_forever()
客户端代码
1 # -*- coding:utf-8 -*- 2 3 4 from socket import * 5 import threading 6 7 HOST = 'localhost' ## 8 PORT=8022 9 BUFSIZ = 1024 ##缓冲区大小 1K 10 ADDR = (HOST,PORT) 11 12 tcpCliSock = socket(AF_INET,SOCK_STREAM) 13 tcpCliSock.connect(ADDR) 14 15 16 class inputdata(threading.Thread): 17 def run(self): 18 while True: 19 data = raw_input('> ') 20 tcpCliSock.send(data) 21 pass 22 23 24 class getdata(threading.Thread): 25 def run(self): 26 while True: 27 data = tcpCliSock.recv(BUFSIZ) 28 print data 29 pass 30 31 32 def main(): 33 myinputd = inputdata() 34 mygetdata = getdata() 35 myinputd.start() 36 mygetdata.start() 37 myinputd.join() 38 mygetdata.join() 39 40 41 if __name__ == '__main__': 42 main()
程序需要先运行服务端在运行多个客户端,多个客户端可已进行通讯