add socket
This commit is contained in:
@@ -33,6 +33,8 @@ var (
|
|||||||
dbFile string
|
dbFile string
|
||||||
dbInit bool
|
dbInit bool
|
||||||
|
|
||||||
|
socketAddress string
|
||||||
|
|
||||||
// rootCmd represents the base command when called without any subcommands
|
// rootCmd represents the base command when called without any subcommands
|
||||||
rootCmd = &cobra.Command{
|
rootCmd = &cobra.Command{
|
||||||
Use: "tele-recv",
|
Use: "tele-recv",
|
||||||
@@ -96,5 +98,6 @@ func initConfig() {
|
|||||||
lograw = viper.GetBool("serial.lograw")
|
lograw = viper.GetBool("serial.lograw")
|
||||||
dbFile = viper.GetString("sqlite.file")
|
dbFile = viper.GetString("sqlite.file")
|
||||||
dbInit = viper.GetBool("sqlite.init")
|
dbInit = viper.GetBool("sqlite.init")
|
||||||
|
socketAddress = viper.GetString("socket.address")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,3 +8,7 @@ serial:
|
|||||||
sqlite:
|
sqlite:
|
||||||
file: telegram.db
|
file: telegram.db
|
||||||
init: true
|
init: true
|
||||||
|
|
||||||
|
|
||||||
|
socket:
|
||||||
|
address: 127.0.0.1:6000
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
const ServerType = "tcp"
|
||||||
|
|
||||||
|
var ServerRunning = false
|
||||||
|
var client net.Conn
|
||||||
|
|
||||||
|
func Listen(address string) {
|
||||||
|
server, err := net.Listen(ServerType, address)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("error in create server ", err)
|
||||||
|
}
|
||||||
|
defer server.Close()
|
||||||
|
log.Println("listen on ", address)
|
||||||
|
for ServerRunning {
|
||||||
|
conn, err := server.Accept()
|
||||||
|
if err != nil {
|
||||||
|
ServerRunning = false
|
||||||
|
log.Fatalln("error in create connection ", err)
|
||||||
|
}
|
||||||
|
if client == nil {
|
||||||
|
client = conn
|
||||||
|
} else {
|
||||||
|
log.Println("client already connected, close")
|
||||||
|
conn.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Write(data string) {
|
||||||
|
defer func() {
|
||||||
|
client.Close()
|
||||||
|
client = nil
|
||||||
|
}()
|
||||||
|
_, err := client.Write([]byte(data))
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error in write data to client socket ", err)
|
||||||
|
client.Close()
|
||||||
|
client = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user