Go Language WebSocket Programming __websocket

Source: Internet
Author: User

Go provides the native WebSocket API, which can then be referenced when you are using the Golang.org/x/net/websocket

, which is also easy to use, directly on the code. code for an echo server

Package main import ("Golang.org/x/net/websocket" "FMT" "Net/http" "flag") type wsserver struct {L Istenaddr String} func (this *wsserver) handler (Conn *websocket. Conn) {fmt. Printf ("A new WS Conn:%s->%s\n", Conn.) Remoteaddr (). String (), Conn. Localaddr (). String ()) var err error for {var reply string err = WebSocket. Message.receive (conn, &reply) If Err!= nil {fmt. PRINTLN ("Receive err:", err.) Error ()) break} fmt. Println ("Received from client:" + Reply) If Err = WebSocket. Message.send (conn, reply); Err!= Nil {fmt. PRINTLN ("Send err:", err.) Error ()) Break}} func (this *wsserver) Start () (Error) {http. Handle ("/ws", WebSocket. Handler (This.handler)) fmt. PRINTLN ("Begin to listen") Err: = http. Listenandserve (this. LISTENADDR, nil) If Err!= nil {fmt. Println ("Listenandserve:", err) return err} FMT. PrintlN (' Start end ') return nil} func main () {addr: = flag. String ("A", "127.0.1.1:12345", "WebSocket Server listen Address") flag. Parse () WSServer: = &wsserver{listenaddr: *addr, Wsserver.start () fmt. PRINTLN ("------End-------")}

In the above code, each new WebSocket Client,server will have a goroutine execution wssever handler function. WebSocket Client Code instance

Package main

import (
    "flag"
    "FMT"
    "Time" "
    golang.org/x/net/websocket"
)

var addr = Flag. String ("addr", "127.0.0.1:12345", "HTTP Service address")

func Main () {
    flag. Parse ()

    URL: = "ws://" + *addr + "/ws"
    origin: = "test://1111111/"
    ws, Err: = WebSocket. Dial (URL, "", origin)
    If Err!= nil {
        FMT. PRINTLN (ERR)
    } go
    timewriter (ws)

    for {
        var msg [512]byte
        _, err: = ws. Read (msg[:])//Here is blocked, waiting for the data to be readable
        if err!= nil {
            FMT. Println ("read:", err)
            return
        }

        fmt. Printf ("Received:%s\n", msg)
    }
}

func timewriter (conn *websocket. Conn) {for
    {time
        . Sleep (time. Second * 2)
        websocket. Message.send (conn, "Hello World")
    }
}

Client code that sends Hello world to server every 2 seconds and then blocks in the Read function. It should be noted that Origin must be "http://1111111/" this standard URI format, otherwise the error "Invalid URI for request". shutdown process, network disconnection, and other unusual conditions shutdown Process

Whether server or client, the shutdown process, to the end of read will immediately receive EOF, to deal with EOF. Network disconnection test
Client and server are deployed on different machines, the client sends data to the server every 2 seconds, and the server spits back to the client when it receives it. In this process, unplug the client's network cable. Test results
After the network is broken, the client can write successfully within a certain period of time, but because the disconnected network is not actually sent out, the data is written to the underlying TCP buffer. After some time, 1 minutes or so, client read returns the error "Read:operation timed out". Write returns "Write:broken pipe". This may be the websocket implementation of go in addition to the timeout mechanism, it is possible to set the underlying TCP so_keepalive, detection of the network is not available. Reconnect the network before Read/write returns an error, and you can continue to send and receive data. This can be explained from the TCP implementation. A TCP connection is not a physical connection, essentially a four-tuple that is maintained by the respective system cores on both ends of the connection. Client disconnection, in a certain period of time will not lead to the release of four of tuples. So when the network cable is connected, this TCP connection can be automatically restored, and continue to perform normal operation. The disconnection is connected to other networks, which is equivalent to breaking the net. This is a good explanation, connecting to other networks, the IP address has changed, the previous four-tuple is not available.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.