• 网络通信_socket


    socket又称套接字

    使用server实现循环通信 代码如下

    import socket
    server = socket.socket()
    server.bind(('192.168.16.33',8000))
    server.listen(5)
    while 1:
        coon,addr = server.accept()
        while 1:
            ret = coon.recv(1024).decode('utf-8')
            print(ret)
            msg = input('内容:').encode('utf-8')
            coon.send(msg)
        coon.close()
    
    server.close()

    客户端如下

    import socket
    client = socket.socket()
    client.connect(('192.168.16.33',8000))
    while 1:
        msg = input('>>>')
        client.send(msg.encode('utf-8'))
        ret = client.recv(1024).decode('utf-8')
        print(ret)
    client.close()

    使用socketserver可以实现并发通信

    import socketserver
    class MY_server(socketserver.BaseRequestHandler):
        def handle(self):
            ret = self.request.recv(1024).decode('utf-8')
            print(ret)
    
    if __name__ == '__main__':
        ip = ('127.0.0.1',8000)
        server = socketserver.ThreadingTCPServer(ip,MY_server)

    使用socket实现通信效果很容易造成黏包现象

    产生黏包现象需要用struct和josn序列化的方式来解决,

    import struct
    import subprocess
    import socket
    server = socket.socket()
    server.bind(('127.0.0.1',8000))
    server.listen(5)
    coon,addr = server.accept()
    cmd = coon.recv(1024).decode('utf-8')
    print(cmd)
    obj = subprocess.Popen(cmd,shell= True,stderr=subprocess.PIPE,stdout=subprocess.PIPE)
    right_obj = obj.stdout.read()
    error_obj = obj.stderr.read()
    date_beyes = len(right_obj + error_obj)
    print(date_beyes)
    struct_date_beyes = struct.pack('i',date_beyes)
    print(struct_date_beyes)
    coon.send(struct_date_beyes)
    coon.send(right_obj +error_obj)
    import socket
    import struct
    client = socket.socket()
    client.connect(('127.0.0.1',8000))
    cmd = input('>>>').encode('utf-8')
    client.send(cmd)
    beyes_struct_len = client.recv(4)
    print(beyes_struct_len)
    beyes_struct_ = struct.unpack('i',beyes_struct_len)[0]
    date = b''
    while len(date) < beyes_struct_:
        form_date = client.recv(1024)
        date += form_date
    print(date.decode('gbk'))

    上图是解决黏包现象的客户端和服务端代码 

  • 相关阅读:
    第十四周学习进度
    第十三周学习进度
    第十二周学习进度条
    从用户体验角度评价所使用的输入法。
    个人博客十
    数组测试 --Junit
    看了build to win之后的感想
    思考题
    数组中最大子数组之和
    使用Espresso进行UI测试
  • 原文地址:https://www.cnblogs.com/baby12138/p/10462983.html
Copyright © 2020-2023  润新知