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): {}!".forma