文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Python3 websocket se

2023-01-31 01:54

关注
原文:https://blog.csdn.net/leemboy/article/details/79449819


     
WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。
       WebSocket通信协议于2011年被IETF定为标准RFC 6455,并被RFC7936所补充规范。

WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。

在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。

当你获取 Web Socket 连接后,你可以通过 send() 方法来向服务器发送数据,并通过 onmessage 事件来接收服务器返回的数据。

以下 API 用于创建 WebSocket 对象。

var Socket = new WebSocket(url, [protocol] );



Websocket Python3 Server实例


#!/usr/bin/env python

import asyncio
import websockets
import json


with open("web_so_cfg.json",'r') as load_f:
    global load_dict
    load_dict = json.load(load_f)
    
ipaddr=load_dict['server_url']
port=load_dict['server_port']
data_file=load_dict['data_file']
help_cmd=load_dict['help_cmd']
load_f.close()

print("ipaddr=",ipaddr)
print("port=",port)
print("data_file=",data_file)

file_name = data_file
top_items_name = ''


with open(file_name, 'r') as load_f:
    global load_dict_2
    load_dict_2 = json.load(load_f)


print('-----------------------------------')
for item in load_dict_2:
    top_items_name=top_items_name+item+'\n'
    print(item,'=',load_dict_2[item])
    
print('-----------------------------------')


async def ift_command_line(websocket, path):
    name = await websocket.recv()
    print("< {}".format(name))

    ift_message = "ift_command_line: {}".format(name)

    ift_message_str=ift_message+"  test msg"
    '''
    await websocket.send(ift_message_str)
    print("> {}".format(ift_message_str))
    '''

    print (name)

    if name == 'help':
        with open("web_so_cfg.json",'r') as load_f:
            load_dict = json.load(load_f)
            help_cmd=load_dict['help_cmd']
        load_f.close()
        help_name='the command help: '+help_cmd
        ift_message = "ift_command_line: {}!".format(help_name)
        await websocket.send(ift_message)
        
    elif name == 'get-json-topitem':
        ift_message = "ift_command_line(from server): {}!".format(top_items_name)
        await websocket.send(ift_message)
    elif 'get-json-value-of' in name:
        str_array=name.split('of')
        item=str_array[1].strip()
        print (item)
        if item in load_dict_2:
            value=load_dict_2[item]
        else:
            value='null'
            
        print(value)
        ift_message = "ift_command_line(from server): {}!".format(value)
        await websocket.send(ift_message)
    else:
        error_infor=name +' is not a command!'
        ift_message = "ift_command_line(from server): {}!".format(error_infor)
        await websocket.send(ift_message)
start_server = websockets.serve(ift_command_line, ipaddr, port)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()


Websocket server配置文件web_so_cfg.json

{
    "server_url": "192.168.8.102",
    "server_port": "8765",
    "data_file": "Handbetrieb_Maske_b.JSON",
    "help_cmd":"get-json-topitem,get-json-value-of <itemname>,get-data,get-name,add-user,mod-user,mod-user-pwd,mod-user-service,create-json-with-name:value,parse-json-with-\"jsonstr\""
 }


Demo中使用的Json文件:Handbetrieb_Maske_b.JSON

{
    "current_tester": "SSTM",
    "current_materdata": "D:\\SVN\\Weishaupt_E01600\\image\\daten\\sw\\M1.sw",
    "specimen_type": "1 Ph",
    "selected_axis": "1",
    "current_power_supply_unit": "Sinamics NT 3Ph 600V/120A",

    "power_supply_controls": {
        "setpoint_voltage": {
            "current_value": 50,
            "unit": "V",
            "min_value": 0,
            "max_value": 600,
            "supported_precision": 0.1
        },
        "setpoint_frequency": {
            "current_value": 45.0,
            "unit": "Hz",
            "min_value": 45.0,
            "max_value": 75.0,
            "supported_precision": 0.1
        }
    },
    "load_machine_controls": {
        "setpoint_speed": {
            "current_value": 0,
            "unit": "rpm",
            "min_value": 0,
            "max_value": 1000,
            "supported_precision": 0.1
        },
        "setpoint_current_limit_torque": {
            "current_value": 0,
            "unit": "Nmm",
            "min_value": 0,
            "max_value": 100,
            "supported_precision": 1
        },
        "setpoint_load_active": {
            "current_value": false
        }
    },
    "specimen_controls": {
        "setpoint_rotation_direction": {
            "current_value": "clockwise",
            "possible_values": [
                "clockwise",
                "counter clockwise"
            ]
        },
        "setpoint_speciment_power_supply_active": {
            "current_value": false
        },
        "setpoint_1uf_condensator_connected": {
            "current_value": false
        },
        "setpoint_2uf_condensator_connected": {
            "current_value": false
        },
        "setpoint_4uf_condensator_connected": {
            "current_value": false
        },
        "setpoint_7uf_condensator_connected": {
            "current_value": false
        },
        "setpoint_10uf_condensator_connected": {
            "current_value": false
        },
        "setpoint_20uf_condensator_connected": {
            "current_value": false
        },
        "setpoint_40uf_condensator_connected": {
            "current_value": false
        }
    },
    "measurement_setup_controls": {
        "setpoint_sample_rate": {
            "current_value": "20 Hz",
            "possible_values": [
                "20 Hz",
                "10 Hz",
                "1 Hz"
            ]
        },
        "setpoint_poweranalyzer_mode_set_to_local": {
            "current_value": false
        },
        "setpoint_countinous_measurement_recording_active": {
            "current_value": false
        }
    },

    "actions": [
        "shutdown_measurement",
        "start_resistance_measurement",
        "store_current_sample"
    ],

    "actual_values": [
        {
            "label": "time",
            "current_value": null,
            "unit": "s"
        },
        {
            "label": "angle",
            "current_value": null,
            "unit": "°"
        },
        {
            "label": "speed",
            "current_value": null,
            "unit": "rpm"
        },
        {
            "label": "torque",
            "current_value": null,
            "unit": "Nmm"
        },
        {
            "label": "p_mech",
            "current_value": null,
            "unit": "kW"
        },
        {
            "label": "frequency",
            "current_value": null,
            "unit": "Hz"
        },
        {
            "label": "voltage",
            "current_value": null,
            "unit": "V"
        },
        {
            "label": "current",
            "current_value": null,
            "unit": "A"
        },
        {
            "label": "p_electric",
            "current_value": null,
            "unit": "kW"
        },
        {
            "label": "Q_1",
            "current_value": null,
            "unit": "kVAR"
        },
        {
            "label": "S_1",
            "current_value": null,
            "unit": "kVA"
        },
        {
            "label": "cos_phi",
            "current_value": null,
            "unit": ""
        },
        {
            "label": "ETA_M",
            "current_value": null,
            "unit": ""
        },
        {
            "label": "Temp_1",
            "current_value": null,
            "unit": "°C"
        },
        {
            "label": "Temp_2",
            "current_value": null,
            "unit": "°C"
        },
        {
            "label": "Temp_3",
            "current_value": null,
            "unit": "°C"
        }
    ]
}


Websocket Python3 Client实例

#!/usr/bin/env python

import asyncio
import websockets
import json
with open("web_so_cfg.json",'r') as load_f:
     load_dict = json.load(load_f)
    
ipaddr=load_dict['server_url']
port=load_dict['server_port']
data_file=load_dict['data_file']
print("ipaddr=",ipaddr)
print("port=",port)
print("data_file=",data_file)

connect_addr_port='ws://'+ipaddr+':'+port
print("connect_addr_port=",connect_addr_port)

async def web_so_op():
    async with websockets.connect(connect_addr_port) as websocket:
        name = input("Enter the cmd--->> ")
        await websocket.send(name)
        print("> {}".format(name))

        greeting = await websocket.recv()
        print("< {}".format(greeting))

while True:
    asyncio.get_event_loop().run_until_complete(web_so_op())

Websocket JavaScript client实例

<!DOCTYPE html>  
<meta charset="utf-8" />

<html> 
<h1>WebSocket Test</h1>  
<head>  
    <script>
        var wsocket; 
  var flag=0;
  var ws_link;
        function Connect(){ 
   var url_port=document.getElementById("msg").value;
   if(flag==0){
    ws_link='ws://'+url_port;
    flag=1;
   }
   document.getElementById("receive_msg").innerHTML=ws_link;
            try{
    
               //wsocket=new WebSocket('ws://192.168.8.101:8765/');  
      wsocket=new WebSocket(ws_link); 
            }catch(e){  
                alert('error');  
                return;  
            }  
            wsocket.onopen = sOpen;  
            wsocket.onerror = sError;
            wsocket.onmessage= sMessage;
            wsocket.onclose= sClose;
        }  
        function sOpen(){
            alert('connect success!');
        }
        function sError(e){
            alert("error " + e);
   document.getElementById("receive_msg").innerHTML=e.data;
        }
        function sMessage(e){  
            alert('server says:' + e.data);
   document.getElementById("receive_msg").innerHTML='server says:' + e.data;
   ;
        }
        function sClose(e){
            alert("connect closed:" + e.code);
        }  
        function Send(){
        
            wsocket.send(document.getElementById("msg").value);
        } 
        function Close(){
            wsocket.close();
        }  
    </script>
</head>  
   
<body>  
<input id="msg" type="text">  
<button id="connect" οnclick="Connect();">Connect</button>  
<button id="send" οnclick="Send();">Send</button> 

<div id="receive_msg"></div>

</body>  
   
</html>  

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯