angular
前端
- 写一个websocket服务
src/app/service/websocket.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class WebsocketService {
private subject = new Subject<any>();
private wsUrl: string = 'ws://localhost/ws?id=myid';
public ws!: WebSocket;
constructor() {
this.wssWSServer(this.subject);
}
wssWSServer(sub:any){
console.log("WebSocket");
this.ws = new WebSocket(this.wsUrl);
this.ws.onopen = function(){
console.log("open创建连接:");
}
this.ws.onmessage = function(e:any){
console.log("收到消息:", e);
}
this.ws.onclose = function(e:any){
console.log("close");
}
this.ws.onerror = function(e:any){
console.log(e);
}
}
wssSendMsg(id:string, type:string, msg: string){
console.log("wsSendMsg enter: " + msg);
this.ws.send(id + type + msg);
}
wssGetMsg(): Observable <string> {
console.log("wsGetMsg called");
return this.subject.asObservable();
}
}
- 其他组件中使用
src/app/service/share.service.ts 任意组件的ts 文件,这里在服务里边写了
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { WebsocketService } from './websocket.service';
@Injectable({
providedIn: 'root'
})
export class ShareService {
private incomingMsg!: Observable<any>;
constructor(private wss: WebsocketService) {
this.incomingMsg = this.wss.wssGetMsg();
this.incomingMsg.subscribe(message => {
var dataObj = eval("(" + message + ")");
console.log(dataObj)
})
}
}
python后端
main.py
from abc import ABC
import tornado.ioloop
import tornado.web
from tornado import httpclient
from tornado import gen
from websocket.ws_server import WsHandler
settings = {
'template_path': 'DIAVS/tornado_web',
'static_path': 'DIAVS/tornado_web/static',
'static_url_prefix': '/static/',
}
application = tornado.web.Application([
(r"/ws", WsHandler),
], **settings)
if __name__ == "__main__":
application.listen(80)
print("tornado启动成功,监听端口:80")
tornado.ioloop.IOLoop.instance().start()
websocket/ws_server.py
import json
import random
from time import sleep
from tornado.websocket import WebSocketHandler
import datetime
import asyncio
import websockets
users = dict()
pyload = {}
def wsSendMsgAll(payload):
print("users=?", users)
for key in users:
users[key].write_message(payload)
def wsSendMsgbyId(id):
pass
class WsHandler(WebSocketHandler):
def open(self):
print("---open: 新连接---")
print(self)
user = self.get_argument("id")
users[user] = self
print("当前用户:", user)
print("所有用户:", users)
def on_message(self, message):
print("---onmessage---")
print("收到Web端消息:", message)
pyload.clear()
def on_close(self):
print("---on close---")
users.remove(self)
def check_origin(self, origin):
return True
|