照貓畫虎,東拼西湊的代碼。python
總結shell
1.python 開始很方便的,就是有些不知從何下手的感受 socket
2.基礎知識沒有,連字符串和列表也分不清楚debug
3.在shell中執行後,使用ctrl+C 終止如何釋放UDP的佔用?orm
#!/bin/python
# -*- coding: cp936 -*-server
#最簡單的udpserverci
import os
import sys
import logging
import socket
import binascii字符串
logger = logging.getLogger("udp server")
logger.setLevel(logging.DEBUG)get
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)it
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
"""
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
"""
"""
分析收到的數據包,避免拆包。
"""
def analy_data(data):
try:
nalu_head=data[16:20]
#print nalu_head
#print binascii.b2a_hex(nalu_head[0]),binascii.b2a_hex(nalu_head[1]),binascii.b2a_hex(nalu_head[2]),binascii.b2a_hex(nalu_head[3])
print ''.join(['%02x ' %ord(c) for c in data[0:32]]) #列表解析
finally:
return 0 #收到完整數據包
def udpserver(port):
try:
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(("",port))
total_data=''
while True:
data,addr = s.recvfrom(8192)
if not data: break
total_data = total_data + data
res = analy_data(total_data)
if res==0:
total_data=''
finally:
s.close()
"""
def main( argv ):
listener = Listener( 7070 )
debug( "waiting for a client" )
try:
while 1:
client = listener.waitforclient()
client.start()
finally:
listener.stop()
"""
if __name__ == "__main__": logger.info("start udp at 2500") udpserver(2500)