用socket连接远程服务器时,有时候会发生远程服务器断开连接,改如何判断?
我用C# TcpClient,有时候server已经关闭,但是TcpClient.connected还是true(比如server的80端口),用什么方法判断比较好?
我用C# TcpClient,有时候server已经关闭,但是TcpClient.connected还是true(比如server的80端口),用什么方法判断比较好?
调试欢乐多
Socket对象在对方断开连接的时候Receive方法会返回一个0字节的数据包。这样就可以判断对方是否断开连接了。
listenshow.Text="主机"+myIP+"端口:8545开始监听......\r\n";
while(true)
{
temp = sock.Accept();
if(temp.Connected == true)
{
listenshow.Text = "与客户建立连接!";
this.send1.Enabled = true;
while(bb)
{
int byteRecv = 0;
try
{
Byte[] bbb=new Byte[64];
byteRecv = temp.Receive(bbb,bbb.Length,0);
if(byteRecv < 1)
{
temp.Close();
temp = null;
listenshow.Text = "与客户断开连接!从新监听!";
this.send1.Enabled = false;
this.showimage.Text = "";
break;
}
string ccc=System.Text.Encoding.BigEndianUnicode.GetString(bbb);
showimage.AppendText(ccc+"\r\n");
} catch(SocketException ex)
{
MessageBox.Show(ex.ToString());
temp.Close();
listenshow.Text = "与客户断开连接。";
this.send1.Enabled = false;
this.showimage.Text = "";
break;
} catch(ObjectDisposedException ex)
{
MessageBox.Show(ex.ToString());
break;
} } }wzd24(牧野)(衣带渐宽终不悔,为伊消得人憔悴) 兄弟帮忙解决的...
那出来让兄弟参考..
这个:http://community.csdn.net/Expert/topic/5524/5524609.xml?temp=.4617731
http://blog.csdn.net/wzd24