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
Posted cucy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了9.3 多客户端TCP相关的知识,希望对你有一定的参考价值。
以上是关于9.3 多客户端TCP的主要内容,如果未能解决你的问题,请参考以下文章