【发布时间】:2019-01-04 08:26:32
【问题描述】:
我是 Golang、Angular (7.1.4) 和 websockets 的新手。我严格按照tutorial 来学习它们,一切都按预期运行。但是,我不明白 Angular 如何在 localhost:4200/* 上为聊天室页面提供服务,其中 * 可以是我输入的任何内容。
编辑:我的主要问题是,考虑到我影响 URL 的唯一地方似乎在 Angular 项目的 socket.service.ts 中的这一行 this.socket = new WebSocket("ws://localhost:12345/ws") 中,这是怎么发生的。我认为这意味着页面应该在 localhost:4200 上加载only,如果有的话。
我阅读了一些 Angular 的文档,我得到的最接近答案的答案是在 routing 的页面上,上面写着“最后一条路由中的 ** 路径是通配符。路由器将选择这个如果请求的 URL 与配置中前面定义的路由的任何路径都不匹配,则路由。”但我没有在任何地方使用过**。事实上,我根本没有按照教程使用过路由。
这是完整的 socket.service.ts 文件:
import { Injectable } from "@angular/core";
import { EventEmitter } from "@angular/core";
@Injectable({
providedIn: "root"
})
export class SocketService {
private socket: WebSocket;
private listener: EventEmitter<any> = new EventEmitter();
public constructor() {
# I think only this line is used to manage the URL.
this.socket = new WebSocket("ws://localhost:12345/ws");
this.socket.onopen = event => {
this.listener.emit({ type: "open", data: event });
};
this.socket.onclose = event => {
this.listener.emit({ type: "close", data: event });
};
this.socket.onmessage = event => {
this.listener.emit({ type: "message", data: JSON.parse(event.data) });
};
}
public send(data: string) {
this.socket.send(data);
}
public close() {
this.socket.close();
}
public getEventListener() {
return this.listener;
}
}
在 Golang 的 main.go 中,只有两行,主要是 http.HandleFunc("/ws", wsPage),与聊天室 URL 相关。基于此,我假设页面也可以加载到 localhost:12345/ws 上。但是去那里会产生“找不到错误的请求 404 页面”。这是我认为与 main.go 相关的代码:
func wsPage(res http.ResponseWriter, req *http.Request) {
conn, error := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}).Upgrade(res, req, nil)
if error != nil {
http.NotFound(res, req)
return
}
client := &Client{id: uuid.NewV4().String(), socket: conn, send: make(chan []byte)}
manager.register <- client
go client.read()
go client.write()
}
func main() {
go manager.start()
# Only these two lines relate to the URL.
http.HandleFunc("/ws", wsPage)
http.ListenAndServe(":12345", nil)
}
有人能解释一下 Angular 在这种情况下是如何管理 URL 的,以及它的 URL 是如何优先于 Golang 的吗?或者指出我正确的文档/阅读材料?谢谢。
【问题讨论】:
-
恐怕我没有完全理解这个问题。你做什么工作?你能指望什么?你观察到什么?
-
@AndreyDyatlov 抱歉,可能有点不清楚。我的主要问题是,考虑到我影响 URL 的唯一地方似乎在这一行 this.socket = new WebSocket("ws://localhost:12345/ws") in socket 怎么会发生这种情况.service.ts 在 Angular 项目中。我认为这意味着页面应该只在 localhost:4200 上加载,如果有的话。