Home > Backend Development > Golang > Learn network programming functions in Go language and implement WebSocket communication

Learn network programming functions in Go language and implement WebSocket communication

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-07-29 17:37:22
Original
1465 people have browsed it

Learn the network programming functions in Go language and implement WebSocket communication

Introduction
Go language, as a powerful programming language, is widely used in the field of network programming. It provides a wealth of network programming functions and libraries, allowing developers to easily implement various network communication functions. This article will introduce some commonly used network programming functions in the Go language and combine examples to implement WebSocket communication.

1. Network programming function

  1. net.Listen
    Function signature: func Listen(network, address string) (Listener, error)
    Purpose: Listen to the specified network address and return a Listener object
    Example:

    listener, err := net.Listen("tcp", "127.0.0.1:8080")
    if err != nil {
     log.Fatal(err)
    }
    defer listener.Close()
    Copy after login
  2. Accept
    Function signature: func (l *TCPListener) Accept() (Conn, error)
    Purpose: Accept the connection request and return a Conn object
    Example:

    conn, err := listener.Accept()
    if err != nil {
     log.Fatal(err)
    }
    defer conn.Close()
    Copy after login
  3. WebSocket protocol
    WebSocket is a protocol for full-duplex communication on a single TCP connection. Allows real-time communication between client and server. The Go language provides the gorilla/websocket library to easily implement WebSocket communication functions.

2. Implement WebSocket communication

  1. Install gorilla/websocketLibrary
    Execute the following command in the command line:

    go get -u github.com/gorilla/websocket
    Copy after login
  2. Server-side code

    package main
    
    import (
     "log"
     "net/http"
    
     "github.com/gorilla/websocket"
    )
    
    var upgrader = websocket.Upgrader{
     ReadBufferSize:  1024,
     WriteBufferSize: 1024,
    }
    
    func websocketHandler(w http.ResponseWriter, r *http.Request) {
     conn, err := upgrader.Upgrade(w, r, nil)
     if err != nil {
         log.Fatal(err)
     }
     defer conn.Close()
    
     for {
         messageType, message, err := conn.ReadMessage()
         if err != nil {
             log.Println(err)
             break
         }
         log.Printf("Received message: %s
    ", message)
    
         if err := conn.WriteMessage(messageType, message); err != nil {
             log.Println(err)
             break
         }
     }
    }
    
    func main() {
     http.HandleFunc("/websocket", websocketHandler)
     log.Fatal(http.ListenAndServe(":8080", nil))
    }
    Copy after login
  3. Client-side code

    package main
    
    import (
     "log"
     "net/url"
    
     "github.com/gorilla/websocket"
    )
    
    func main() {
     u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/websocket"}
     conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
     if err != nil {
         log.Fatal(err)
     }
     defer conn.Close()
    
     for i := 0; i < 5; i++ {
         message := []byte("Hello from client")
         if err := conn.WriteMessage(websocket.TextMessage, message); err != nil {
             log.Fatal(err)
         }
    
         _, receivedMessage, err := conn.ReadMessage()
         if err != nil {
             log.Fatal(err)
         }
         log.Printf("Received message from server: %s", receivedMessage)
     }
    }
    Copy after login

Run the above two code files, This enables communication between the client and the server based on the WebSocket protocol. The client will send a message to the server, receive the message back from the server, and repeat 5 times.

Summary
This article introduces some commonly used network programming functions in the Go language, and implements WebSocket communication with examples. By learning this knowledge, we can better understand and apply it to actual network programming. Whether we are developing web applications or other network communication scenarios, mastering these network programming functions will greatly improve our development efficiency. It is hoped that readers can further understand the network programming features of Go language through learning, so that they can be flexibly applied in actual projects.

The above is the detailed content of Learn network programming functions in Go language and implement WebSocket communication. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template