GO语言实现简单TCP服务的方法
本文实例讲述了GO语言实现简单TCP服务的方法。分享给大家供大家参考。具体实现方法如下:
packagemain
import(
"net"
"fmt"
)
var( maxRead=1100
msgStop =[]byte("cmdStop")
msgStart =[]byte("cmdContinue")
)
funcmain(){
hostAndPort:="localhost:54321"
listener:=initServer(hostAndPort)
for{
conn,err:=listener.Accept()
checkError(err,"Accept:")
goconnectionHandler(conn)
}
}
funcinitServer(hostAndPortstring)*net.TCPListener{
serverAddr,err:=net.ResolveTCPAddr("tcp",hostAndPort)
checkError(err,"Resolvingaddress:portfailed:'"+hostAndPort+"'")
listener,err:=net.ListenTCP("tcp",serverAddr)
checkError(err,"ListenTCP:")
println("Listeningto:",listener.Addr().String())
returnlistener
}
funcconnectionHandler(connnet.Conn){
connFrom:=conn.RemoteAddr().String()
println("Connectionfrom:",connFrom)
talktoclients(conn)
for{
varibuf[]byte=make([]byte,maxRead+1)
length,err:=conn.Read(ibuf[0:maxRead])
ibuf[maxRead]=0//topreventoverflow
switcherr{
casenil:
handleMsg(length,err,ibuf)
default:
gotoDISCONNECT
}
}
DISCONNECT:
err:=conn.Close()
println("Closedconnection:",connFrom)
checkError(err,"Close:")
}
functalktoclients(tonet.Conn){
wrote,err:=to.Write(msgStart)
checkError(err,"Write:wrote"+string(wrote)+"bytes.")
}
funchandleMsg(lengthint,errerror,msg[]byte){
iflength>0{
fori:=0;;i++{
ifmsg[i]==0{
break
}
}
fmt.Printf("Receiveddata:%v",string(msg[0:length]))
fmt.Println(" length:",length)
}
}
funccheckError(errorerror,infostring){
iferror!=nil{
panic("ERROR:"+info+""+error.Error())//terminateprogram
}
}
希望本文所述对大家的Go语言程序设计有所帮助。
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短