美文网首页
Golang 搭建Tcp服务器

Golang 搭建Tcp服务器

作者: 富竹 | 来源:发表于2020-04-01 11:02 被阅读0次

数据库使用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)
 }
}

相关文章

网友评论

      本文标题:Golang 搭建Tcp服务器

      本文链接:https://www.haomeiwen.com/subject/qneouhtx.html