python - 有没有办法以标准方式编写 websocket 代码?
问题描述
似乎每一种语言和它所有的 web socket 库都使用自己稍微不同的古怪方法来编写它的 web socket 代码,代码略有不同,语言略有不同,有的更长,有的更短,有的更简单,有的更难,但有没有共识,有没有办法让我的 python 和 node.js web socket 代码服务器相同,并使它们等于浏览器的内置套接字,或者我必须学习每个不同的代码?
示例:1:Python 与 asyncio
import websockets
# create handler for each connection
async def handler(websocket, path):
data = await websocket.recv()
reply = f"Data recieved as: {data}!"
await websocket.send(reply)
start_server = websockets.serve(handler, "localhost", 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
示例 2:带有 ws 的 Node.js
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
enter code here
客户端示例:
const socket = new WebSocket('ws://localhost:8000');
socket.addEventListener('open', function (event) {
socket.send('Connection Established');
});
socket.addEventListener('message', function (event) {
console.log(event.data);
});
const contactServer = () => {
socket.send("Initialize");
问题是它们都如此不同,有没有办法解决这个问题
解决方案
我已经意识到这些模块本身并没有添加“太多”,实际上只是使用它自己的语言格式,尽管这些示例有点高级
一般公式是
导入模块或库(主要是特定于语言的,一些差异取决于模块)
启动 http 服务器(特定于语言)
在 http 服务器上挂载模块(主要是特定于语言的,一些差异取决于模块)
发送和接收信息,通常采用以下格式,我将使用 socket.io 作为示例,因为它是我所知道的,但大多数使用类似的格式,更改主要是特定于语言的
//to send connection.send("recieve_this", information_being_sent) //to receive socket.on("recieve_this", function(information_being_sent){ //receives (information_being_sent) and starts a function that you can do work on })
这是一个使用 javascript 和 socket.io 运行的完整服务器的示例
var http = require('http'); //important for hosting a server on http
const { Server } = require("socket.io");//requires the imported socket module
const server = http.createServer(function(recieve, send){
}).listen(8000) //starts http server on port 8000 (can be any port you like)
const connection = new Server(server); //creates a variable called connection and mounts socket.io's Server to http's server
//to send
connection.send("recieve_this", information_being_sent)
//to receive
socket.on("recieve_this", function(information_being_sent){
//receives (information_being_sent) and starts a function that you can do work on
})
这是所有服务器代码,您还需要向客户端发送脚本,阅读文档。
推荐阅读
- spring-mvc - hibernate Validator 不验证模型类
- python - 删除或合并熊猫数据框中的多索引列而不丢失数据
- python - zlib TypeError:需要一个类似字节的对象,而不是“str”
- php - 无法在 PHP 站点中检索 MySQL 数据
- unity3d - 如何让强化学习代理学习永无止境的跑步者?
- javascript - Jquery弹出模型内容向下滚动问题
- html - 项目加载时更改 Typescript 中的样式
- java - 没有可用的节点 elasticsearch
- javascript - 保存会话变量错误的时间间隔
- javascript - 无法从javascript设置fancybox iframe