使用Go搭建Tcp服务器,数据库使用MongoDB,代码复制修改参数即可使用。
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"net"
)
type Message struct {
_Id bson.ObjectId
Client string
Msg string
}
func main() {
session, coll := ConnectMongo()
defer session.Close()
lner, err := net.Listen("tcp", "192.168.124.65:8080")
if err != nil {
fmt.Println("Listener create error: ", err)
return
}
fmt.Println("Waiting for client...")
for {
conn, err := lner.Accept()
if err != nil {
fmt.Println("Accept error: ", err)
return
}
go handleConnection(coll, conn)
}
}
func handleConnection(coll *mgo.Collection, conn net.Conn) {
clientAddr := conn.RemoteAddr().String()
fmt.Println("Connection success. Client address: ", clientAddr)
defer conn.Close()
for {
buffer := make([]byte, 1024)
recvLen, err := conn.Read(buffer)
if err != nil {
fmt.Println("Read error: ", err, clientAddr)
return
}
strBuffer := string(buffer[:recvLen])
fmt.Println("Client message: ", strBuffer)
InsertMongo(coll, clientAddr, strBuffer)
}
}
func ConnectMongo() (*mgo.Session, *mgo.Collection) {
session, err := mgo.Dial("192.168.8.10:27017")
if err != nil {
panic(err)
}
session.SetMode(mgo.Monotonic, true)
coll := session.DB("tcp_server").C("tcp_data")
return session, coll
}
func InsertMongo(coll *mgo.Collection, client, msg string) {
insertMsg := Message{
Client: client,
Msg: msg,
}
err := coll.Insert(&insertMsg)
if err != nil {
fmt.Println("Insert mongodb error: ", err)
}
}
有疑问加站长微信联系(非本文作者)