本文實(shí)例講述了GO語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單TCP服務(wù)的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
復(fù)制代碼 代碼如下:
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
}
}
希望本文所述對(duì)大家的Go語(yǔ)言程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- Go 并發(fā)實(shí)現(xiàn)協(xié)程同步的多種解決方法
- 詳解Golang 中的并發(fā)限制與超時(shí)控制
- golang實(shí)現(xiàn)并發(fā)數(shù)控制的方法
- Go語(yǔ)言如何并發(fā)超時(shí)處理詳解
- GO語(yǔ)言并發(fā)編程之互斥鎖、讀寫鎖詳解
- Go語(yǔ)言并發(fā)技術(shù)詳解
- Go語(yǔ)言中TCP/IP網(wǎng)絡(luò)編程的深入講解
- 6行代碼快速解決golang TCP粘包問(wèn)題
- Go語(yǔ)言服務(wù)器開發(fā)之簡(jiǎn)易TCP客戶端與服務(wù)端實(shí)現(xiàn)方法
- 在Go中構(gòu)建并發(fā)TCP服務(wù)器