原來是本人的畢業設計。現在拿出來共用下。先申明,作者是lust,老師如果在網上搜到這段代碼可不要說我的畢業設計是網上copy滴哈。
用python做了一個P2P的簡單實現,可以通過在服務端註冊公網IP和連接埠後,直接和其它用戶端進行通訊。目前只能在完全對稱NAT下成功實現,在window 2003 nat服務和vmware內建的nat下測試成功。用iptables的nat不可行。
初學Python,代碼不是很完善,比如logout沒有寫,只供參考。
Server端代碼:
#!/usr/bin/python #coding:utf-8 import socket, sys, SocketServer, threading, thread, time SERVER_PORT = 1234sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', SERVER_PORT)) user_list = [] def server_handle(): while True: cli_date, cli_pub_add = sock.recvfrom(8192) now_user = [] headder = [] cli_str = {} headder = cli_date.split('\t') for one_line in headder: str = {} str = one_line args = str.split(':') cli_str[args[0]] = args[1] if cli_str['type'] == 'login' : del cli_str['type'] now_user = cli_str now_user['cli_pub_ip'] = cli_pub_add[0] now_user['cli_pub_port'] = cli_pub_add[1] user_list.append(now_user) toclient = 'info#%s login in successful , the info from server'%now_user['user_name'] sock.sendto(toclient,cli_pub_add) print '-'*100 print "%s 已經登入,公網IP:%s 連接埠:%d\n"%(now_user['user_name'],now_user['cli_pub_ip'],now_user['cli_pub_port']) print "以下是已經登入的使用者列表" for one_user in user_list: print '使用者名稱:%s 公網ip:%s 公網連接埠:%s 私網ip:%s 私網連接埠:%s'%(one_user['user_name'],one_user['cli_pub_ip'],one_user['cli_pub_port'],one_user['private_ip'],one_user['private_port']) elif cli_str['type'] == 'alive': pass elif cli_str['type'] == 'logout' : pass elif cli_str['type'] == 'getalluser' : print '-'*100 for one_user in user_list : toclient = 'getalluser#username:%s pub_ip:%s pub_port:%s pri_ip:%s pri_port:%s'%(one_user['user_name'],one_user['cli_pub_ip'],one_user['cli_pub_port'],one_user['private_ip'],one_user['private_port']) sock.sendto(toclient,cli_pub_add) if __name__ == '__main__': thread.start_new_thread(server_handle, ()) print '伺服器處理序已啟動,等待客戶串連' while True: for one_user in user_list: toclient = 'keepconnect#111' sock.sendto(toclient,(one_user['cli_pub_ip'],one_user['cli_pub_port'])) time.sleep(1)