douchen1988 2013-12-28 12:11
浏览 37
已采纳

Go中的网络编程

I'm studying Go for network programming. The problem is Go documentation is too simple. For example, I don't know when to use net.DialTCP, and when to use TCPListener object to AcceptTCP, what's the difference? How about client communicate with another client? Not client to server.

  • 写回答

2条回答 默认 最新

  • dongping6974 2013-12-28 12:43
    关注

    Connecting

    In Go, you use the Dial function from net to connect to a remote machine.

    net.Dial("tcp","google.com:80")
    net.Dial("udp","tracker.thepiratebay.org:6969")
    net.Dial("ip","kremvax.su")
    net.Dial("unix","/dev/log")
    

    This gives you an abstract Conn object that represents the connection you just established. Conn implements the ReadWriteCloser interface from io and a couple of other functions. You can use this object to send and receive data.

    Listening

    To listen, i.e. open a port, you use the Listen function from net. Calling Listen gives you a Listener object. Use Accept to accept incoming connections. Accept returns another Conn object that can be used as above.

    ls, err := net.Listen("tcp",":1337")
    if err != nil {
        // port probably blocked, insert error handling here
    }
    
    conn, err := ls.Accept()
    if err != nil {
        // error handling
    }
    
    conn.Write("Hello, world!")
    

    DialTCP and ListenTCP

    These functions give you more control over TCP connections. I suggest you to only use them if they are definitly needed for your program as Dial and Listen are simpler, more generic and easily allow you to adapt your program to other types of network connections.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?