zoukankan      html  css  js  c++  java
  • UDP简单初识+socketserver 模块实现服务端并发

    ####UDP初试

    ##服务端
    import socket


    server = socket.socket(type=socket.SOCK_DGRAM)
    server.bind(('127.0.0.1',8080))

    while True:
        data, addr = server.recvfrom(1024)
        print(data.decode('utf-8'))
        server.sendto(data.upper(),addr)
        
    ##客户端

    import socket

    client = socket.socket(type=socket.SOCK_DGRAM)
    server_addr = ('127.0.0.1',8080)

    while True:
        # msg = input('>>>:')
        # msg = '客户端1:%s'%msg
        # client.sendto(msg.encode('utf-8'),server_addr)
        client.sendto(b'hello',server_addr)
        data,addr = client.recvfrom(1024)
        print(data)

    ##TCP服务端
    import socketserver

    class MyBaby(socketserver.BaseRequestHandler):
        def handle(self):
            while True:
                try:
                    data = self.request.recv(1024)
                    print(data)
                    self.request.send(data.upper())
                except ConnectionResetError:
                    break

    if __name__ == '__main__':
        server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyBaby)
        server.serve_forever()
        
        
        
     
    # UDP 服务端
    #socketserver使用
    import socketserver

    class MyUdpServer(socketserver.BaseRequestHandler):
        def handle(self):
            while True:
                data, sock = self.request
                print(data)
                sock.sendto(data.upper(), self.client_address)


    if __name__ == '__main__':
        server = socketserver.ThreadingUDPServer(('127.0.0.1', 8080), MyUdpServer)
        server.serve_forever()
        
    #客户端
    import socket
    import time

    client = socket.socket()
    client.connect(('127.0.0.1',8080))

    while True:
        client.send(b'hello')
        data = client.recv(1024)
        print(data)
        time.sleep(1)


  • 相关阅读:
    OS模块
    利用一个random模块生成一个随机验证码功能
    random模块
    模块2
    模块module
    Java笔记汇总
    学习路上——技术书籍摸爬滚打
    web前端知识汇总——持续更新
    Python之路——进入Python学习
    Python细节备忘——时常拾遗以及关键点
  • 原文地址:https://www.cnblogs.com/1832921tongjieducn/p/10969801.html
Copyright © 2011-2022 走看看