zoukankan      html  css  js  c++  java
  • 基于udp实现套接字通信、基于socketserver实现并发(udp和tcp)

    一、基于udp实现套接字通信

    服务端:

    from socket import *

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

    while True:
    data, client_addr = server.recvfrom(1024)
    print('====>',data,client_addr)
    server.sendto(data.upper(), client_addr)

    server.close()

    客户端:
    from socket import *
    client=socket(AF_INET,SOCK_DGRAM)#数据报协议-》udp

    while True:
    msg=input('>>:').strip() #msg='' 空数据也可以发送(其实不是空数据,每个数据都有报头,udp不会发送空数据)
    client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
    data,server_client=client.recvfrom(1024)
    print(data)
    client.close()



    #udp协议没有粘包问题,不能用来传大的数据 每次传送最好不大于512字节


    二、基于socketserver实现并发(udp和tcp)

    服务端(tcp):
    import socketserver

    class MyHandler(socketserver.BaseRequestHandler):
    def handle(self):
    #通信循环
    while True:
    # print(self.client_address)
    # print(self.request) #self.request=conn

    try:
    data=self.request.recv(1024)
    if len(data) == 0:break
    self.request.send(data.upper())
    except ConnectionResetError:
    break

    if __name__ == '__main__':
    s=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyHandler,bind_and_activate=True)

    s.serve_forever() # 代表连接循环
    # 循环建立连接,每建立一个连接就会启动一个线程(服务员)+调用Myhanlder类产生一个对象,
    # 调用该对象下的handle方法,专门与刚刚建立好的连接做通信循

    客户端(tcp):

    import socket

    phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    phone.connect(('127.0.0.1',8080)) # 指定服务端ip和端口

    while True:
    msg=input('>>: ').strip() #msg=''
    # msg = 'client22222' # msg=''
    if len(msg) == 0:continue
    phone.send(msg.encode('utf-8'))
    data=phone.recv(1024)
    print(data)

    phone.close()



    服务端(udp):
    import socketserver

    class MyHandler(socketserver.BaseRequestHandler):
    def handle(self):
    #通信循环
    # print(self.client_address)
    # print(self.request)

    data=self.request[0]
    print('客户消息',data)
    self.request[1].sendto(data.upper(),self.client_address)


    if __name__ == '__main__':
    s=socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyHandler)
    s.serve_forever()

    客户端(udp):
    import socket

    client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #数据报协议-》udp

    while True:
    msg=input('>>: ').strip() #msg=''
    # msg='client444444'

    client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
    data,server_addr=client.recvfrom(1024)
    print(data)

    client.close()





  • 相关阅读:
    Hibernate: Encountered a duplicated sql alias [] during auto-discovery of a native-sq
    “Uncaught TypeError: string is not a function”
    Jquery Ajax 返回数据类型变成document
    浏览器URL编码
    SQL Server 多条查询结果组合
    (转)No row with the given identifier exists问题的解决
    观nginx与lvs负载均衡的较量
    Nginx启动、关闭、重新加载脚本
    数据挖掘-分词入门
    HBase 专题技术收录
  • 原文地址:https://www.cnblogs.com/kingyanan/p/9296180.html
Copyright © 2011-2022 走看看