# -*- coding: utf-8 -*-
from socket import *
server = socket(AF_INET, SOCK_DGRAM) # udp以数据报的形式传输数据
ip_port = ("127.0.0.1", 8001) # 服务端的IP和端口
server.bind(ip_port) # 绑定ip和端口
while 1: # 通讯循环
client_msg, client_addr = server.recvfrom(1024)
print("from client %s msg: %s" % (client_msg, client_addr))
server.sendto(client_msg.upper(), client_addr)
# -*- coding: utf-8 -*-
from socket import *
client = socket(AF_INET, SOCK_DGRAM)
server_addr = ("127.0.0.1", 8001)
while 1: # 通讯循环
inp = input(">>:").strip()
client.sendto(inp.encode(), server_addr)
server_msg, server_addr = client.recvfrom(1024)
print("from server %s msg: %s" % (server_msg, server_addr))
# -*- coding: utf-8 -*-
import socketserver
class MyUDPhandler(socketserver.BaseRequestHandler):
def handle(self):
client_msg, server = self.request
server.sendto(client_msg.upper(), self.client_address)
if __name__ == '__main__':
ip_port = ("127.0.0.1", 8001) # 服务端的IP和端口
server = socketserver.ThreadingUDPServer(ip_port, MyUDPhandler)
server.serve_forever()