HI guys:
I'm a new to GO.I wish to make a a high concurrency socket server using Go, that's my code:
package main
import (
"fmt"
"os"
"net"
"time"
"runtime"
)
var sem = make(chan int, 1000)
func init() {
for i := 0; i < 1000; i++ {
sem <- 1
}
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
service := ":10000"
tcpAddr,err := net.ResolveTCPAddr("tcp4", service)
if err != nil {
fmt.Println("error ResolveTcpAddr:", err.Error())
os.Exit(-1)
}
listener, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
fmt.Println("error listenTcp:", err.Error())
os.Exit(-1)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accept:", err.Error())
os.Exit(-1)
}
<- sem
go HandleRequest(conn)
}
}
func HandleRequest(conn net.Conn) {
defer func(){
sem<-1
}()
defer conn.Close()
buf := make([]byte, 1024)
for {
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
read_len, err := conn.Read(buf)
if err != nil {
fmt.Println("error read:", err.Error())
break
}
if read_len == 0 {
fmt.Println("read 0 bytes:", err.Error())
break
}
if _, err = conn.Write([]byte("ok")); err != nil {
fmt.Println("error write:", err.Error())
break
}
buf = make([]byte, 1024)
}
}
for every request , the server makes a goroutine to handle it.
then I did the Load Tetsing by LoadRunner.
the problem is:
1 start running the test script . the LR's Trans/sec line always fell to bottom rapidly after 7 minutes(see below), and LR show errors that connection reset
2 "netstat -ntu|grep 10000|grep ESTABLISHED|wc -l" always show 30, and after the errors , it change less
3 try to stace related threads, they stay in the "FUTEX_WAIT" status.
is the problem clear? did I make something wrong in the code or what should do for the problem? Is there wonderful library for socket server in go?
the problem is troubling me.
