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

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
    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.

    点赞 评论

相关推荐