go 的tcp的应用层代码看起来极为简单
1,多个协程同时Accept , 不知道这种实现有没有什么问题
2,多个协程同时处理网络IO事件, 貌似意味着, 有多少个连接过来就需要有多少个协程了, 对于go来说,一个进程支持足够都的协程, 远远大于带宽的限制
服务端代码
package main
import (
"net"
"time"
"fmt"
)
func ca(){
a := recover()
fmt.Println("Catch", a)
}
func main(){
defer ca()
fmt.Println("main start")
L, e:=net.Listen("tcp", "127.0.0.1:7878")
if e != nil{
fmt.Println("this is null")
panic("claa null")
}
for index:=0; index<10; index++{
go handleAccept(L, index)
}
for{
time.Sleep(1e9)
}
}
func handleAccept(L net.Listener, index int){
for{
fmt.Println("Accept index=", index)
a, ae := L.Accept()
if ae != nil{
fmt.Println("Accept index quit", index)
break
}
go handleConnect(a)
}
}
func handleConnect(c net.Conn){
for{
var buffer []byte = make([]byte, 1024)
len, re := c.Read(buffer)
if len == 0 && "EOF" == re.Error(){
fmt.Println("quit")
c.Close()
break
}
var dd string = string(buffer)
fmt.Println(len, re, "data:", dd)
}
}
客户端代码:
package main
import (
"net"
"time"
"strconv"
"fmt"
)
func Send(){
conn, e := net.Dial("tcp", "127.0.0.1:7878")
if e != nil{
panic("e is nil")
}
var index int = 0
for{
var data string = strconv.Itoa(index)
len, e:=conn.Write([]byte(data))
if e != nil{
fmt.Println(len, e, "Close Connct")
conn.Close()
}
index = index+1
time.Sleep(1e9)
}
}
func main(){
fmt.Println("client main start")
for index:=0; index<100; index++{
go Send()
}
for{
time.Sleep(1e9)
}
}