「青鋒」springboot、python、nodejs+websocket技術實戰分享

青鋒開源地址(開源多版基礎架構)

青鋒目前開源了一下版本架構:

springboot+layui+thymeleaf版本

springboot+layui+jsp版本

springboot+vue ant design 前後端分離版本

springcloud+

vue/react

ant design 前後端分離雙版本。

青鋒springboot 家譜系統。

碼雲搜尋青鋒:青鋒 (msxy) - Gitee。com

一、node之websocket技術實現

1、安裝nodejs-websocket

npm install nodejs-websocket

2、核心程式碼實現

var ws = require(‘nodejs-websocket’);var port=3000var server = ws。createServer(function(conn){ //受到連線觸發// console。log(‘new connection’); conn。on(“text”,function(str){ // 收到資訊觸發 接收 // console。log(“received:”+str) boardcast(str) // 廣播訊息 // conn。sendText(str) // 傳送 資料 // }) conn。on(“close”,function(code,reason){ // 斷開連線觸發 // console。log(“connection closed”) }) conn。on(“error”,function(err){ // 出錯觸發 // console。log(“header err”) console。log(err) }) function boardcast(str){ // 廣播 // // server。connections 儲存每個連線進來的使用者 // server。connections。forEach(function(conn){ // 。forEach 是呼叫數組裡每個元素 // conn。sendText(str) }) }})。listen(port)console。log(“websocket server listen port is ” + port)

3、HTML端程式碼實現

可能遇到的問題:ws://localhost:8088 可以正常訪問 改為

ws://192。168。1。120:8088 就不可以訪問,

原因就是獲取不到session資訊

解決方法:需要瀏覽器輸入的專案地址和建立websocket連線的地址一樣

青鋒websocket技術實現

請輸入內容:

二、python之websocket技術實現

1、安裝依賴庫 websocket, websocket-client

pip install websocket pip3 install websocket-client

2、服務端程式碼實現

#!/usr/bin/env python# encoding: utf-8import websocketsimport asyncioclass WSserver(): async def handle(self, websocket, path): recv_msg = await websocket。recv() print(“i received %s” % recv_msg) await websocket。send(‘server send ok’) def run(self): ser = websockets。serve(self。handle, “127。0。0。1”, “3000”) asyncio。get_event_loop()。run_until_complete(ser) asyncio。get_event_loop()。run_forever()ws = WSserver()ws。run()

3、客戶端程式碼實現

#!/usr/bin/python# -*- coding: UTF-8 -*-import jsonimport timefrom websocket import create_connectionclass WSClient: def __init__(self, address): self。ws = create_connection(address) def send(self, params): print(“Sending 。。。”) self。ws。send(json。dumps(params)) print(“Sending Data: {}”。format(params)) print(“Reeiving。。。”) result = self。ws。recv() print(“Received ‘{}’”。format(result)) def quit(self): self。ws。close()t = str(time。time() * 1000)。split(“。”)[0]params1 = { “version”: 1, “msgNo”: t, “machNo”: “U040119110001”, “cmd”: 1, “time”: t}if __name__ == ‘__main__’: address = “ws://127。0。0。1:3000/ws” # 初始化 web_client = WSClient(address) web_client。send(params1) # 斷開連線 web_client。quit() print(r‘send end’)

springboot+websocket請看下一章整合。

「青鋒」springboot、python、nodejs+websocket技術實戰分享

「青鋒」springboot、python、nodejs+websocket技術實戰分享

「青鋒」springboot、python、nodejs+websocket技術實戰分享