udp多线程

#!/usr/bin/python
# coding: utf-8
import socket, SocketServer, threading, thread, time
CLIENT_PORT = 4321
local_ip = socket.gethostbyname(socket.gethostname())
SERVER_IP = "14.116.214.241"
SERVER_PORT = 9999
user_list = {}
local_uname = ""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto('type:alive', ('14.116.214.241', 9999))
to_user_ip=SERVER_IP
to_user_port=SERVER_PORT
def server_handle():
	#print '客户端线程已经启动 , 等待其它客户端连接'
	while True:
		#recvfrom 要求发生在send 或者sendto 之后,要不然,不知道收什么地址和端口
		data,addr = sock.recvfrom(1024)
		data_str = data.split('#')
		data_type = data_str[0]
		data_info = data_str[1]
		if data_type=='keepconnect':
			messeg = 'type:alive'
			sock.sendto(messeg, addr)
		elif data_type=='info':
			del data_str[0]
			print data_info  
		elif data_type=='getalluser':
			data_sp = data_info.split(' ')
			user_name = data_sp[0].split(':')[1]
			del data_sp[0]
			user_list[user_name] = {}
			for one_line in data_sp:
				arg = one_line.split(':')
				user_list[user_name][arg[0]] = arg[1]
		elif data_type=='echo' :
			print data_info


if __name__ == '__main__':
	
	thread.start_new_thread(server_handle, ())
	time.sleep(0.1)
	cmd = raw_input(u'输入指令>>')
	while True:
		args = cmd.split(' ')

		if args[0] == 'login':
			user_name = args[1]
			local_uname = args[1]
			address = "private_ip:%s private_port:%d" % (local_ip, CLIENT_PORT)
			headder = "type:login\tuser_name:%s\tprivate_ip:%s\tprivate_port:%d" % (user_name,local_ip,CLIENT_PORT)
			sock.sendto(headder, (SERVER_IP, SERVER_PORT))
			
		elif args[0] == 'getalluser':
			headder = "type:getalluser\tuser_name:al"
			sock.sendto(headder,(SERVER_IP,SERVER_PORT))
			print'获取用户列表中。。。'
			time.sleep(1)
			for one_user in user_list:
				print"username:%s pub_ip:%s pub_port:%s pri_ip:%s pri_port:%s"%(one_user,user_list[one_user]['pub_ip'],user_list[one_user]['pub_port'],user_list[one_user]['pri_ip'],user_list[one_user]['pri_port'])
                        
		elif args[0] == 'connect':
			user_name = args[1]
			to_user_ip = user_list[user_name]['pub_ip']
			to_user_port = int(user_list[user_name]['pub_port'])
			
		elif args[0] =='echo':
			m = ' '.join(args[1:])
			message = 'echo#from %s:%s'%(local_uname,m)
			print message
			sock.sendto(message, (to_user_ip, to_user_port))
			time.sleep(0.1)  
		cmd = raw_input(u'\n输入指令>>')

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'a udp server example which send time to client.'
import socket,thread,time

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 地址一定要0.0.0.0 也是 INADDR_ANY 。绑定端口:9999
sock.bind(('0.0.0.0', 9999))
print 'Bind UDP on 9999...'
list_client=[]
def add_addr(addr):
	global list_client
	list_client.append(addr)
def del_addr(addr):
	global list_client
	list_client.remove(addr)

def server_handle():
	while True:
		cli_date, cli_pub_add = sock.recvfrom(8192)
		now_user = []
		headder = []
		cli_str = {}
		headder = cli_date.split('\t')
		
		str1 = {}
		str1 = headder[0]
		args = str1.split(':')
		cli_str[args[0]] = args[1]
		if cli_str['type'] == 'login' :
			#del cli_str['type']
			for one_line in headder:
					str1 = one_line
					args = str1.split(':')
					cli_str[args[0]] = args[1]
			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)
			add_addr(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 list_client:
				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 list_client :
				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'服务器进程已启动,等待客户连接\n输入你要发送:'
	while True:
		for one_user in list_client:
			toclient = 'keepconnect#111'
			sock.sendto(toclient,(one_user['cli_pub_ip'],one_user['cli_pub_port']))  
			#mystr=raw_input("请输入给地址:%s:%s:"%oneAddr)		
			#s.sendto('input,%s'%mystr,oneAddr)
			time.sleep(1)

你可能感兴趣的:(python)