github.com/ergo-services/ergo@v1.999.224/tests/udp_test.go (about) 1 package tests 2 3 import ( 4 "fmt" 5 "net" 6 "testing" 7 "time" 8 9 "github.com/ergo-services/ergo" 10 "github.com/ergo-services/ergo/etf" 11 "github.com/ergo-services/ergo/gen" 12 "github.com/ergo-services/ergo/node" 13 ) 14 15 var ( 16 resUDPChan = make(chan interface{}, 2) 17 ) 18 19 type testUDPHandler struct { 20 gen.UDPHandler 21 } 22 23 func (r *testUDPHandler) HandlePacket(process *gen.UDPHandlerProcess, data []byte, packet gen.UDPPacket) { 24 resUDPChan <- data 25 return 26 } 27 28 type testUDPServer struct { 29 gen.UDP 30 } 31 32 func (ts *testUDPServer) InitUDP(process *gen.UDPProcess, args ...etf.Term) (gen.UDPOptions, error) { 33 var options gen.UDPOptions 34 options.Handler = &testUDPHandler{} 35 options.Port = 10101 36 37 return options, nil 38 } 39 40 func TestUDP(t *testing.T) { 41 fmt.Printf("\n=== Test UDP Server\n") 42 fmt.Printf("Starting nodes: nodeUDP1@localhost: ") 43 node1, err := ergo.StartNode("nodeUDP1@localhost", "cookies", node.Options{}) 44 defer node1.Stop() 45 if err != nil { 46 t.Fatal("can't start node", err) 47 } else { 48 fmt.Println("OK") 49 } 50 51 fmt.Printf("...starting process (gen.UDP): ") 52 udpProcess, err := node1.Spawn("udp", gen.ProcessOptions{}, &testUDPServer{}) 53 if err != nil { 54 t.Fatal(err) 55 } 56 fmt.Println("OK") 57 58 fmt.Printf("...send/receive data: ") 59 c, err := net.Dial("udp", "localhost:10101") 60 if err != nil { 61 t.Fatal(err) 62 } 63 defer c.Close() 64 data := []byte{1, 2, 3, 4, 5} 65 c.Write(data) 66 waitForResultWithValue(t, resUDPChan, data) 67 68 fmt.Printf("...stopping process (gen.UDP): ") 69 udpProcess.Kill() 70 if err := udpProcess.WaitWithTimeout(time.Second); err != nil { 71 t.Fatal(err) 72 } 73 fmt.Println("OK") 74 }