dongmang3961 2017-10-09 09:23
浏览 105

Golang UDP和TCP彼此并排

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

  • 写回答

1条回答 默认 最新

  • doushi7819 2017-10-09 15:12
    关注

    As noted by putu you need some concurrency to get it working properly.

    NodeJS works with callbacks by default, which means that once you pass a function as a parameter to a function it will release the main loop to the next instruction. This is why NodeJS apps have the object.method(function(){}) pattern. To achieve something similar to this in Go, you need to wrap the TCP and UDP portion of the program in a separate goroutine with a infinite loop each.

    For a simple proof the concept, do something like this:

    ...
    go func(){
      // paste your tcp code here 
    }()
    ...
    go func(){
      // paste your udp code here
    }()
    

    That "go" instruction says to the compiler that a portion of code should run concurrently. In a real-world project, you will put that portion of code in a proper function and just call it by name from your main function:

    ...
    go serveTCP();
    go serve UDP();
    ...
    

    More about concurrency in go here => https://tour.golang.org/concurrency/1

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!