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)


 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com