Go语言服务器开发之简易TCP客户端与服务端实现方法
本文实例讲述了Go语言服务器开发之简易TCP客户端与服务端实现方法。分享给大家供大家参考。具体实现方法如下:
Go语言具备强大的服务器开发支持,这里示范了最基础的服务器开发:通过TCP协议实现客户端与服务器的通讯。
一服务端,为每个客户端新开一个goroutine
funcServerBase(){
fmt.Println("Startingtheserver...")
//createlistener
listener,err:=net.Listen("tcp","192.168.1.27:50000")
iferr!=nil{
fmt.Println("Errorlistening:",err.Error())
return
}
//listenandacceptconnectionsfromclients:
for{
conn,err:=listener.Accept()
iferr!=nil{
fmt.Println("Erroraccepting:",err.Error())
return
}
//createagoroutineforeachrequest.
godoServerStuff(conn)
}
}
funcdoServerStuff(connnet.Conn){
fmt.Println("newconnection:",conn.LocalAddr())
for{
buf:=make([]byte,1024)
length,err:=conn.Read(buf)
iferr!=nil{
fmt.Println("Errorreading:",err.Error())
return
}
fmt.Println("Receivedatafromclient:",string(buf[:length]))
}
}
二客户端连接服务器,并发送数据
funcClientBase(){
//openconnection:
conn,err:=net.Dial("tcp","192.168.1.27:50000")
iferr!=nil{
fmt.Println("Errordial:",err.Error())
return
}
inputReader:=bufio.NewReader(os.Stdin)
fmt.Println("Pleaseinputyourname:")
clientName,_:=inputReader.ReadString('\n')
inputClientName:=strings.Trim(clientName,"\n")
//sendinfotoserveruntilQuit
for{
fmt.Println("Whatdoyousendtotheserver?TypeQtoquit.")
content,_:=inputReader.ReadString('\n')
inputContent:=strings.Trim(content,"\n")
ifinputContent=="Q"{
return
}
_,err:=conn.Write([]byte(inputClientName+"says"+inputContent))
iferr!=nil{
fmt.Println("ErrorWrite:",err.Error())
return
}
}
}
注:由于LiteIDE不支持同时运行多个程序,所以需要在终端通过gorun命令来同时运行服务端和(一个或多个)客户端,可观察到服务器对并发访问的支持。
希望本文所述对大家的Go语言程序设计有所帮助。