使用socketserver的ThreadingUDPServer、ThreadingTCPServer实现收发消息和文件

本文章采用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
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值