#!/usr/bin/env python3
#file name: threadtest.py
# -*- coding:utf8 -*-
# -version:1.0-
import threading, time, socket
class Server():
‘‘‘接收消息的服务器类‘‘‘
def __init__(self, port):
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.server.bind(("", self.port))
while True:
data, addr = self.server.recvfrom(1024)
if addr[0] == "127.0.0.1": continue
print("\nMessage Comming: {}\tFrom: {}".format(data, addr))
class Client():
‘‘‘发送消息的客户端类‘‘‘
def __init__(self, port):
self.port = port
self.host = "localhost"
self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def _sendToServer(self, msg):
self.client.sendto(msg.encode("utf-8"), (self.host, self.port))
def reciveMsg():
‘‘‘处理接收消息的函数‘‘‘
try:
serv = Server(55553)
except BaseException as e:
print(str(e.args))
def sendMsg():
‘‘‘处理发送消息的函数‘‘‘
try:
clit = Client(55553)
while True:
msg = input("MSG-> ")
clit._sendToServer(msg)
except BaseException as e:
print(str(e.args))
thread_list = []
def main():
global thread_list
try:
recive_thread = threading.Thread(target = reciveMsg, name = "recive")
recive_thread.start()
thread_list.append(recive_thread)
send_thread = threading.Thread(target = sendMsg, name = "send")
send_thread.start()
thread_list.append(send_thread)
except BaseException as e:
print(str(e.args))
if __name__=="__main__":
main()