GO语言实现简单TCP服务的方法
程序员文章站
2023-02-16 22:01:51
本文实例讲述了go语言实现简单tcp服务的方法。分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:
package main
import (
"net...
本文实例讲述了go语言实现简单tcp服务的方法。分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:
package main
import (
"net"
"fmt"
)
var ( maxread = 1100
msgstop = []byte("cmdstop")
msgstart = []byte("cmdcontinue")
)
func main() {
hostandport := "localhost:54321"
listener := initserver(hostandport)
for {
conn, err := listener.accept()
checkerror(err, "accept: ")
go connectionhandler(conn)
}
}
func initserver(hostandport string) *net.tcplistener {
serveraddr, err := net.resolvetcpaddr("tcp", hostandport)
checkerror(err, "resolving address:port failed: '" + hostandport + "'")
listener, err := net.listentcp("tcp", serveraddr)
checkerror(err, "listentcp: ")
println("listening to: ", listener.addr().string())
return listener
}
func connectionhandler(conn net.conn) {
connfrom := conn.remoteaddr().string()
println("connection from: ", connfrom)
talktoclients(conn)
for {
var ibuf []byte = make([]byte, maxread + 1)
length, err := conn.read(ibuf[0:maxread])
ibuf[maxread] = 0 // to prevent overflow
switch err {
case nil:
handlemsg(length, err, ibuf)
default:
goto disconnect
}
}
disconnect:
err := conn.close()
println("closed connection:" , connfrom)
checkerror(err, "close:" )
}
func talktoclients(to net.conn) {
wrote, err := to.write(msgstart)
checkerror(err, "write: wrote " + string(wrote) + " bytes.")
}
func handlemsg(length int, err error, msg []byte) {
if length > 0 {
for i := 0; ; i++ {
if msg[i] == 0 {
break
}
}
fmt.printf("received data: %v", string(msg[0:length]))
fmt.println(" length:",length)
}
}
func checkerror(error error, info string) {
if error != nil {
panic("error: " + info + " " + error.error()) // terminate program
}
}
希望本文所述对大家的go语言程序设计有所帮助。
上一篇: go语言中range用法