2022-11-07 19:01:00 +00:00
|
|
|
package conn
|
|
|
|
|
|
|
|
import (
|
2022-11-07 23:02:36 +00:00
|
|
|
"bufio"
|
2022-11-07 19:01:00 +00:00
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
Port = ":3030"
|
|
|
|
)
|
|
|
|
|
|
|
|
func StartSimple(handler func(conn net.Conn)) error {
|
2022-11-17 19:49:25 +00:00
|
|
|
l, err := net.Listen("tcp4", Port)
|
2022-11-07 19:01:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer l.Close()
|
|
|
|
|
2022-11-17 19:49:25 +00:00
|
|
|
fmt.Println(fmt.Sprintf("Listening TCP on port %s", Port))
|
2022-11-07 19:01:00 +00:00
|
|
|
|
|
|
|
for {
|
|
|
|
c, err := l.Accept()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
go handler(c)
|
2022-11-17 19:49:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func StartSimpleUDP(handler func(*net.UDPConn, *net.UDPAddr, []byte), buffSize int) error {
|
|
|
|
srv, err := net.ResolveUDPAddr("udp4", Port)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
c, err := net.ListenUDP("udp4", srv)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer c.Close()
|
|
|
|
|
|
|
|
fmt.Println(fmt.Sprintf("Listening UDP on port %s", Port))
|
|
|
|
|
|
|
|
buf := make([]byte, buffSize)
|
|
|
|
for {
|
|
|
|
n, addr, err := c.ReadFromUDP(buf)
|
2022-11-07 19:01:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-11-17 19:49:25 +00:00
|
|
|
go handler(c, addr, buf[:n])
|
2022-11-07 19:01:00 +00:00
|
|
|
}
|
|
|
|
}
|
2022-11-07 23:02:36 +00:00
|
|
|
|
|
|
|
func ReadAndRespond(c net.Conn, process func([]byte) []byte) error {
|
|
|
|
defer c.Close()
|
|
|
|
sc := bufio.NewScanner(c)
|
|
|
|
for sc.Scan() {
|
|
|
|
response := process(sc.Bytes())
|
|
|
|
_, err := c.Write(response)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if err := sc.Err(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|