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 模电中二极管,三极管和电容的应用
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像
  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused
  • ¥20 关于web前端如何播放二次加密m3u8视频的问题
  • ¥15 使用百度地图api 位置函数报错?
  • ¥15 metamask如何添加TRON自定义网络