is it possible to use TCP and UDP with each other in a single script? I need some of my packages to send and receive with TCP and some of them with UDP
func main() {
//
// ─── TCP ────────────────────────────────────────────────────────────────────
//
// Listen for incoming connections.
l, err := net.Listen("tcp", "localhost"+":"+"3000")
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
// Close the listener when the application closes.
defer l.Close()
fmt.Println("Listening on " + "localhost" + ":" + "3000")
for {
// Listen for an incoming connection.
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
os.Exit(1)
}
// Handle connections in a new goroutine.
go gotcp.HandleRequest(conn)
//go handler(conn)
}
//
// ─── UDP ────────────────────────────────────────────────────────────────────
//
// then we should check which struct is empty and fill them
/* Lets prepare a address at any address at port 10001*/
ServerAddr, err := net.ResolveUDPAddr("udp", ":3000")
goudp.CheckError(err)
/* Now listen at selected port */
ServerConn, err := net.ListenUDP("udp", ServerAddr)
goudp.CheckError(err)
defer ServerConn.Close()
buf := make([]byte, 1024)
for {
n, addr, err := ServerConn.ReadFromUDP(buf)
//fmt.Println("Received ", string(buf[0:n]), " from ", addr)
if err != nil {
fmt.Println("Error: ", err)
}
// *** broadcasting
//start := time.Now()
if v, ok := goudp.RRoom()[djr]; ok {
//fmt.Println("get room name ", v)
go goudp.BroadCast(string(buf[0:n]), djr, ServerConn, v)
//delete(R, "x")
//go sendResponse(ServerConn, v.UserAddr1)
}
//elapsed := time.Since(start)
//log.Printf("Binomial took %s", elapsed)
}
}
EDIT: By passing tcp part or udp part in a function and call it like go tcpServer() we can use Both UDP and TCP with each other