zoukankan      html  css  js  c++  java
  • day 29(作业)

    # 服务端
    import socket
    import struct
    import json
    from threading import Thread
    
    server = socket.socket()
    server.bind(
        ('127.0.0.1', 9608)
    )
    server.listen(5)
    
    
    def my_server(conn):
        while True:
            try:
                headers = conn.recv(4)
                if not headers:
                    continue
                data_len = struct.unpack('i', headers)[0]
                bytes_data = conn.recv(data_len)
                back_dic = json.loads(bytes_data.decode('utf-8'))
                if back_dic['msg'] == 'q':
                    break
                print(f'{back_dic["name"]}:{back_dic["msg"]}')
                msg1 = back_dic["msg"]
                msg = msg1.upper()
                to_dic = {'name': 'logan', 'msg': msg}
                json_dic = json.dumps(to_dic)
                bytes_dic = json_dic.encode('utf-8')
                send_dic = struct.pack('i', len(bytes_dic))
                conn.send(send_dic)
                conn.send(bytes_dic)
            except Exception as e:
                print(e)
                break
    
    
    if __name__ == '__main__':
        while True:
            conn, addr = server.accept()
            t = Thread(target=my_server, args=(conn,))
            t.start()
    
    
    # 客户端
    import socket
    import struct
    import json
    
    client = socket.socket()
    client.connect(
        ('127.0.0.1', 9608)
    )
    while True:
        try:
            msg = input('发送内容:')
            if msg == 'q':
                break
            dic = {'name': '用户1', 'msg': msg}
            bytes_dic = json.dumps(dic)
            send_dic = bytes_dic.encode('utf-8')
            send_len = struct.pack('i', len(send_dic))
            client.send(send_len)
            client.send(send_dic)
            headers = client.recv(4)
            data_len = struct.unpack('i', headers)[0]
            bytes_data = client.recv(data_len)
            back_dic = json.loads(bytes_data.decode('utf-8'))
            print(f'{back_dic["name"]}:{back_dic["msg"]}')
        except Exception as e:
            print(e)
            break
    client.close()
    
    
  • 相关阅读:
    异常处理 try catch throw(C++)
    Kubernetes轻量级日志收集系统LokiStack
    第一章.java
    第四章.选择结构(二)
    java语法
    第三章if选择结构
    第二章.数据类型变量名和运算符
    【转载】跳槽七诫
    【转载】修改shell终端提示信息
    ubuntu11.10面板上输入法图标消失解决办法
  • 原文地址:https://www.cnblogs.com/luocongyu/p/11722221.html
Copyright © 2011-2022 走看看