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.
Go中的网络编程
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- dongping6974 2013-12-28 12:43关注
Connecting
In Go, you use the
Dial
function fromnet
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 theReadWriteCloser
interface fromio
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. CallingListen
gives you aListener
object. UseAccept
to accept incoming connections.Accept
returns anotherConn
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
andListen
are simpler, more generic and easily allow you to adapt your program to other types of network connections.本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 高价求中通快递查询接口
- ¥15 解决一个加好友限制问题 或者有好的方案
- ¥15 关于#java#的问题,请各位专家解答!
- ¥15 急matlab编程仿真二阶震荡系统
- ¥20 TEC-9的数据通路实验
- ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
- ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
- ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
- ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
- ¥15 如何实现H5在QQ平台上的二次分享卡片效果?