douyan4470 2019-01-03 05:25
浏览 139
已采纳

Angular如何使用Golang和websockets管理URL?

I'm new to Golang, Angular (7.1.4), and websockets. I'm following this tutorial strictly to learn them, and everything runs as expected. However, I don't understand how Angular serves the chat room page at localhost:4200/*, where * can be anything I type.

Edit: my primary question is, how does this happen given that the only place where I've affected the URL at all seems to be in this line this.socket = new WebSocket("ws://localhost:12345/ws") in socket.service.ts in the Angular project. I think this means the page should load only on localhost:4200, if anywhere.

I read some of Angular's documentation, and the closest I've come to an answer is on its page on routing, where it says "The ** path in the last route is a wildcard. The router will select this route if the requested URL doesn't match any paths for routes defined earlier in the configuration." But I've not used ** anywhere. In fact, I've not used routing at all following the tutorial.

Here is the full socket.service.ts file:

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;
  }
}

In main.go in Golang, only two lines, and primarily http.HandleFunc("/ws", wsPage), relate to the chat room URL. Based on this, I assumed that the page can also load on localhost:12345/ws. But going there produces "Bad Request 404 page not found". Here is the code I think is relevant from 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)
}

Can someone explain how Angular manages URLs in this instance and how its URL takes precedence over Golang's? Or point me to the right documentation/reading material? Thanks.

  • 写回答

1条回答 默认 最新

  • dongshuiga2826 2019-01-04 00:26
    关注

    The websocket is opened from the code that is run in your browser, not from the browser directly (i.e. web address that will return a file, html document, or something of the like).

    The other key thing to note here is the protocol:

    "ws://localhost:12345/ws"
    

    The ws:// is the websocket protocol that the Angular code uses to comunicate with the server. You cannot access a websocket directly with your browser's URL bar because it does not know how to handle a websocket connection on its own (only http or https, connections for example).

    The websocket is being "served" by a Go application, and the Angular application is being served by either Node (if you are running it locally, using ng serve) or via a static hosting environment (like AWS or Google Cloud). When you access the URL at which the Angular application is being served, the Angular code is downloaded to your browser and the Routing system takes control. In the case of a default Angular application, there is a wildcard route, as you mentioned, which will direct any and all paths (the stuff after the hostname and port after a slash) to the root component (which is generally the main AppComponent).

    You can setup different routing schemes with varying paths and many routes, however, you will have to do some research to discover what will work for your application/design. You can have a look here for more info.

    TL;DR

    You need to separate the concepts of the two programs in your mind: one is an Angular App running in your browser, and the other is a Go App running on a server (or your local machine). Hence the reason you are referring to two different ports on your local machine: the 12345 port is where the Golang chat server is accepting incoming connections (via the ws:// websocket protocol), and the 4200 port is where Node.js is listening for incoming connections to serve the Angular HTML/CSS/JS bundle.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配