本文章采用socketserver.ThreadingUDPServer、socketserver.ThreadingTCPServer实现UDP收发文本、TCP收发文件的功能。
只有一个工具类文件socketUtil.py
1.ThreadingUDPServer、ThreadingTCPServer是另起两个线程来同时运行的
2.UdpRequestHandler、TcpRequestHandler里的类方法Creator(cls, *args, **kwargs)是为了将外部类当做参数传入才需要的,便于执行完网络任务后调用外部类的其他函数以做出反应,比如ClassName.onNewDataArrive()。
# coding=utf-8
import os
import time
import uuid
import json
import threading
import socket
import socketserver
class SocketUtil(object):
def __init__(self, god, udpPort=23333, tcpPort=23335):
super(SocketUtil, self).__init__()
self.god = god
self.udpPort = udpPort # 用于收发文本消息
self.tcpPort = tcpPort # 用于接收文件
self.localIP = self.getLocalIP()
# self.initUdpServerAndClient()
# self.initTcpServerAndClient()
def getLocalMacAddress(self):
'''获得本机MAC地址'''
mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
return "-".join([mac[e:e + 2] for e in range(0, 11, 2)])
def getLocalHostName(self):
'''获得本机计算机名称'''
return socket.gethostname()
def getLocalIP(self):
'''获取本地主机IP'''
return self.getIPByHostName(self.getLocalHostName())
def getIPByHostName(self, remoteHostName):
'''获取域名对应的IP'''
ip = None
try:
ip = socket.gethostbyname(remoteHostName)
except socket.error as e:
print("getIPByHostName %s:%s" % (remoteHostName, e.value))
finally:
return ip
def getHostnameByIP(self, ip):
'''根据IP获取其计算机名称'''
hostname = None
try:
# gethostbyaddr返回一个包含三个元素的元组(给定地址的主要的主机名、同一IP地址的可选的主机名的一个列表、
# 关于同一主机的同一接口的其它IP地址的一个列表),比如:('Administrator', [], ['192.168.1.6'])
hostname = socket.gethostbyaddr(ip)[0]
except socket.herror as e:
print("getHostnameByIP %s:%s" % (ip, e.value))
finally:
return hostname
def ping(self, ip):
'''ping指定IP,判断是否ping得通
ping2次,等待时间为1s'''
result = os.system('ping -n 2 -w 1 %s' % ip)
if result:
return False
else:
return True
def multitask_thread(self, func, args=(), join