9.3 多客户端TCP

Posted cucy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了9.3 多客户端TCP相关的知识,希望对你有一定的参考价值。


package main

import (
    "bufio"
    "fmt"
    "io"
    "net"
)

func main() {

    l, err := net.Listen("tcp", ":8080")
    if err != nil {
        panic(err)
    }
    ID := 0
    for {
        fmt.Println("Waiting for client...")
        conn, err := l.Accept()
        if err != nil {
            panic(err)
        }
        fmt.Printf("Client ID: %d connected.\n", ID)
        go func(c net.Conn, clientID int) {
            fmt.Fprintf(conn, "Welcome client ID: %d \n", clientID)
            for {
                msg, err := bufio.NewReader(conn).ReadString(‘\n‘)
                if err != nil {
                    fmt.Println(err)
                    break
                }
                _, err = io.WriteString(conn, "Received: "+string(msg))
                if err != nil {
                    fmt.Println(err)
                    break
                }
            }
            fmt.Println("Closing connection")
            conn.Close()
        }(conn, ID)
        ID++
    }

}

/*

telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is ‘^]‘.
Welcome client ID: 1
dfsdaf
Received: dfsdaf
dsfasnf
Received: dsfasnf
sdfa
Received: sdfa


*/

以上是关于9.3 多客户端TCP的主要内容,如果未能解决你的问题,请参考以下文章

网络编程案例多任务版TCP服务端程序开发

Linux-TCP编程流程-Socket编程-单线程实现TCP客户端和服务端交互-多进程实现TCP客户端和服务端交互

python TCP多客户端连接

TCP案例代码

TCP案例代码

多任务版TCP服务端程序开发案例+源码