Python3 websocket server与client及javascript client通信实现原理


    
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> 


  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,JavaScriptPython可以通过WebSocket进行通信WebSocket是一种全双工、双向通信协议,可以在Web浏览器和服务器之间创建实时通信。以下是实现JavaScriptPython之间的WebSocket通信的一些步骤: 1. 在Python中,使用WebSocket库(例如:websocket-server)创建WebSocket服务器,并监听指定端口。 2. 在JavaScript中,使用WebSocket API创建WebSocket客户端,并连接到上述服务器。 3. 通过WebSocket连接发送和接收数据。在Python中,可以使用WebSocket库提供的send()和recv()方法来发送和接收数据;在JavaScript中,可以使用WebSocket对象的send()和onmessage()方法来发送和接收数据。 下面是一个简单的示例代码,演示如何在JavaScriptPython之间使用WebSocket通信Python 代码: ``` from websocket_server import WebsocketServer # 当WebSocket客户端连接时触发 def new_client(client, server): print("New client connected and was given id %d" % client['id']) # 当WebSocket客户端发送消息时触发 def message_received(client, server, message): print("Message received from client: %s" % message) server.send_message_to_all("Echo: %s" % message) # 创建WebSocket服务器 server = WebsocketServer(8080, host='localhost') server.set_fn_new_client(new_client) server.set_fn_message_received(message_received) # 启动WebSocket服务器 server.run_forever() ``` JavaScript 代码: ``` // 创建WebSocket客户端 var socket = new WebSocket("ws://localhost:8080/"); // 当WebSocket连接打开时触发 socket.onopen = function(event) { console.log("WebSocket opened"); socket.send("Hello, server!"); }; // 当WebSocket接收到消息时触发 socket.onmessage = function(event) { console.log("Message received from server: " + event.data); }; // 当WebSocket连接关闭时触发 socket.onclose = function(event) { console.log("WebSocket closed"); }; ``` 在这个例子中,WebSocket服务器在本地主机上的8080端口上运行。当WebSocket客户端连接时,服务器将触发new_client()回调函数。当客户端发送消息时,服务器将触发message_received()回调函数,并向所有客户端发送一个回复消息。在JavaScript代码中,我们创建了一个WebSocket客户端,并在连接打开时发送一条消息,当接收到服务器消息时打印它。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值