目標
本文目標是以Node.js建立Websocket Server,並以Python3 Websocket Client連入
需求
安裝Node.js Websocket
在終端機輸入npm install websocket
即可安裝完畢,下面是它的github:
https://github.com/theturtle32/WebSocket-Node
即可安裝完畢,下面是它的github:
https://github.com/liris/websocket-client
儲存成server.js
https://github.com/theturtle32/WebSocket-Node
安裝Python3 Websocket
在終端機輸入pip3 install websocket
即可安裝完畢,下面是它的github:
https://github.com/liris/websocket-client
實做
server.js Websocket Server
//引入http websocket
var http = require('http');
var ws = require('websocket').server;
// 建立server 並監聽Port 12345
var PORT = 12345;
var server = http.createServer().listen(PORT)
// 產生websocketServer
webSocketServer = new ws({
httpServer: server
});
//當使用者連入時 觸發此事件
webSocketServer.on('request', function(request) {
var connection = request.accept('echo-protocol', request.origin);
//當websocket server收到訊息時 觸發此事件
connection.on('message', function(message) {
console.log(message)
connection.send("我收到了: " + message.utf8Data);
});
//當使用者socket連線中斷時 例如:關閉瀏覽器 觸發此事件
connection.on('close', function(reasonCode, description) {
console.log('Close');
});
});
儲存成server.js
client.py Client端連線
import websocket
#收到server傳來的message的callback
def onMessage(ws, msg):
print("收到了從server傳來的message:" + msg)
#與server建立連線後的callback
def onOpen(ws):
sendMessage = '安安我是python'
ws.send(sendMessage)
#server的HOST
HOST = 'ws://127.0.0.1:12345'
#與server約定好的protocol server端也要設定
SUBPROTOCOLS = ['echo-protocol']
#建立websocket
ws = websocket.WebSocketApp(HOST, subprotocols = SUBPROTOCOLS, on_open = onOpen, on_message = onMessage)
#一直執行
ws.run_forever()
輸入
node server.js & (&是在背景執行)
python3 client.py
即可看到結果
有什麼問題歡迎留言
沒有留言:
張貼留言