GolangNote

Golang笔记

用Go实现一个长连接的例子

Permalink

用Go实现一个长连接的思路是这样的:

  • 创建一个套接字对象, 指定其 IP 以及端口.
  • 开始监听套接字指定的端口.
  • 如有新的客户端连接请求, 则建立一个 goroutine, 在 goroutine 中, 读取客户端消息, 并转发回去, 直到客户端断开连接
  • 主进程继续监听端口.

实现参考代码

Go: 长连接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main

import (
    "bufio"
    "fmt"
    "net"
    "time"
)

func main() {
    var tcpAddr *net.TCPAddr

    tcpAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:9999")

    tcpListener, _ := net.ListenTCP("tcp", tcpAddr)

    defer tcpListener.Close()

    for {
        tcpConn, err := tcpListener.AcceptTCP()
        if err != nil {
            continue
        }

        fmt.Println("A client connected : " + tcpConn.RemoteAddr().String())
        go tcpPipe(tcpConn)
    }

}

func tcpPipe(conn *net.TCPConn) {
    ipStr := conn.RemoteAddr().String()
    defer func() {
        fmt.Println("disconnected :" + ipStr)
        conn.Close()
    }()
    reader := bufio.NewReader(conn)

    for {
        message, err := reader.ReadString('\n')
        if err != nil {
            return
        }

        fmt.Println(string(message))
        msg := time.Now().String() + "\n"
        b := []byte(msg)
        conn.Write(b)
    }
}

本文网址: https://golangnote.com/topic/120.html 转摘请注明来源

Related articles

Go Modules 使用备忘

简单说 Go Modules 就是包管理,从 go1.11 开始支持,可以不需要gopath存在,环境变量`GO111MODULE`,默认为 `auto` 项目存在 `go.mod` 则使用 go module ,否则使用GOPATH 和 vendor 机制。...

Write a Comment to "用Go实现一个长连接的例子"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 32ms