码迷,mamicode.com
首页 > 其他好文 > 详细

9.3 多客户端TCP

时间:2018-03-27 01:47:13      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:escape   har   tin   test   err   ...   code   source   string   


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

标签:escape   har   tin   test   err   ...   code   source   string   

原文地址:https://www.cnblogs.com/zrdpy/p/8654850.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!