Skip to content

Instantly share code, notes, and snippets.

@yangzhe1991
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yangzhe1991/c43f66aba140d651ffde to your computer and use it in GitHub Desktop.
Save yangzhe1991/c43f66aba140d651ffde to your computer and use it in GitHub Desktop.
tcp test server&client
package main
import (
"runtime"
"log"
"os"
"strconv"
"time"
"net"
"fmt"
"sync/atomic"
)
var msgCount int64
var count int64
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
log.Println("./fakeclient addr numofclient")
num, _ := strconv.Atoi(os.Args[2])
c:=time.Tick(time.Second)
go func(){
for {
<-c
log.Printf("connCount %d, goroutine count %d, msgCount %d\n", count,runtime.NumGoroutine(), msgCount)
}
}()
for i := 1; i <= num; i++ {
go handleClient(i)
}
for {
time.Sleep(time.Hour)
}
}
func handleClient(i int) {
c, err := net.Dial("tcp", fmt.Sprintf("%s:%d", os.Args[1], i%100+20001))
if err!=nil{
log.Panic(err)
}
atomic.AddInt64(&count,int64(1))
data:=make([]byte,100)
buf := make([]byte,500)
c.Write(data)
for {
for l := 0; l < 500; {
if n, err := c.Read(buf[l:500]); err != nil {
log.Println(err)
return
} else {
l += n
}
}
atomic.AddInt64(&msgCount,1)
c.Write(data)
}
}
package main
import (
"fmt"
"net"
"log"
"time"
"runtime"
"sync"
)
func main(){
runtime.GOMAXPROCS(runtime.NumCPU())
tick := time.Tick(time.Second)
go func() {
for {
<-tick
log.Println(len(list))
}
}()
for i := 20001; i <= 20100; i++ {
ln, _ := net.Listen("tcp", fmt.Sprintf(":%d", i))
go func() {
for {
c, err := ln.Accept()
if err != nil {
log.Println(err, "accept new tcp connection failed")
}
ch := make(chan byte,10)
register(ch)
go handleClientConn(c, ch)
}
}()
}
ln2, _ := net.Listen("tcp", ":19000")
for {
c, _ := ln2.Accept()
c.Close()
broadcast()
}
}
var list []chan byte
var lock sync.Mutex
func register( c chan byte){
lock.Lock()
list=append(list,c)
lock.Unlock()
}
func broadcast(){
lock.Lock()
for _,c:=range list{
c<-0
}
lock.Unlock()
}
func handleClientConn(c net.Conn,ch chan byte){
data:=make([]byte,500)
buf := make([]byte,100)
for l := 0; l < 100; {
if n, err := c.Read(buf[l:100]); err != nil {
log.Println(err)
return
} else {
l += n
}
}
for{
<-ch
c.Write(data)
for l := 0; l < 100; {
if n, err := c.Read(buf[l:100]); err != nil {
log.Println(err)
return
} else {
l += n
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment