python 客戶端點對點通信小案例


點對點通訊分為客戶端和服務器,多個客戶端通過服務器進行信息的交流

服務器端代碼  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()

程序需要先運行服務端在運行多個客戶端,多個客戶端可已進行通訊

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM