英文:
Check for server reachability in Golang conn.Write
问题
我正在开发一个应用程序,尝试将一些数据发送到远程服务器。一旦我获得主机名,我通过使用net.Dialer.DialContext
解析主机名来建立连接。一旦解析了主机名,我就继续使用conn.Write
方法向连接写入数据。
conn, err := d.DialContext(ctx, string(transport), addr)
_, err := client.conn.Write([]byte(msg))
遇到的错误:我发现由于某些问题,我无法ping通我的服务器。令人惊讶的是,通过DialContext获得的conn在执行conn.Write
时没有报错,并且它继续向同一连接写入数据。
有人可以帮助我修改写入方法,以便在目标服务器不可达时得到错误提示吗?
英文:
I am working on an application that tries to send some data to a remote server. Once I get the hostname, I get a connection by resolving the hostname using net.Dialer.DialContext
. Once, I resolve the hostname, I keep on using conn.Write
method to write data to the connection.
conn, err := d.DialContext(ctx, string(transport), addr)
_, err := client.conn.Write([]byte(msg))
Error faced: I observed that due to some issues, I was not able to ping my server. Surprisingly, conn obtained from DialContext did not complain while doing conn.Write
and it kept writing to the same connection.
Can someone help me in how to modify my writing methods in order to get an error in case the destination server is not reachable?
答案1
得分: 1
从这个UDP连接示例中:
> 一个“已连接”的UDP套接字可以模拟发送失败的最佳方法是保存ICMP响应,并在下一次写入时将其作为错误返回。
因此,尝试进行第二次conn.Write
(用于测试),以确认这次确实会出现错误。
英文:
From this UDP connection example
> the best a "connected" UDP socket can do to simulate a send failure is to save the ICMP response, and return it as an error on the next write.
So try and (for testing) make a second conn.Write
, to confirm that you would indeed get an error this time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论