数据库使用MongoDB
,代码复制修改Tcp服务器ip
和数据库地址
即可使用,修改点已在代码里标注。
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") // 这里的tcp服务ip需要改
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") // 这里的mongodb服务器需要改
if err != nil {
panic(err)
}
session.SetMode(mgo.Monotonic, true)
coll := session.DB("tcp_server").C("tcp_data") // 这里的mongodb数据库和数据表需要改
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)
}
}
网友评论