silverlight socket 等待主机开机的问题

enterzhuang 2013-01-18 10:11:16

public void start()
{

syn = SynchronizationContext.Current;


if (string.IsNullOrEmpty(ipaddress) || string.IsNullOrWhiteSpace(ipaddress))
{
MessageBox.Show("通讯IP地址不能为空");
return;
}
IPAddress ip = IPAddress.Parse(ipaddress);
IPEndPoint ipe = new IPEndPoint(ip, sPort);
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
socketEventArg = new SocketAsyncEventArgs()
{
RemoteEndPoint = new IPEndPoint(ip, sPort)
};

socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(socketEventArg_Completed);
clientSocket.ConnectAsync(socketEventArg);
if (timer == null)
timer = new Timer(new TimerCallback(StartReceive), null, 2000, 2000);
}
int sInterval = 0;
public void StartReceive(object o)
{
try
{
if (clientSocket.Connected == true)
{
socketEventArg.SetBuffer(byteReceive, 0, byteReceive.Length);
clientSocket.ReceiveAsync(socketEventArg);
}
else
{
sInterval = sInterval + 1;
if (sInterval == 3)
{
sInterval = 0;
clientSocket.ConnectAsync(socketEventArg);
}
}
}
catch
{ }

}
int sReadtime = 0;
void socketEventArg_Completed(object sender, SocketAsyncEventArgs e)
{
switch (e.LastOperation)
{
case SocketAsyncOperation.Connect:
if (e.SocketError !=SocketError.Success)
{

clientSocket.ConnectAsync(socketEventArg);
return;
}
e.SetBuffer(byteReceive, 0, byteReceive.Length);
clientSocket.ReceiveAsync(e);
break;

case SocketAsyncOperation.Receive:
string strText = System.Text.Encoding.UTF8.GetString(e.Buffer, 0, e.Buffer.Length);
if (string.IsNullOrEmpty(strText))
{
//clientSocket.Close();
}
else
{
DogMsg.SendTwoMsg("end");
if (string.IsNullOrEmpty(strText))
return;
if (strText.IndexOf("\0") > 0)
{
strText = strText.Substring(1, strText.IndexOf("\0") - 1);
}
syn.Post(DoThing, strText);


}


break;
case SocketAsyncOperation.None:
isSend = false;
break;
}

}



如是开始连不上主机使用clientSocket.ConnectAsync(socketEventArg);
用定时器进行连接,但只连了二次就不再连了,就算主机开了也没法连接,请帮忙,谢谢
...全文
141 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Architecture Net 2013-01-22
  • 打赏
  • 举报
回复
看看是不是由于第一次连接时未释放该端口的连接,导致第二次连接时端口被占用~
jv9 2013-01-19
  • 打赏
  • 举报
回复
如果初始能够连接成功,说明代码应该没有问题,二次重复连接失败,需要看端口当前是否开放,连接是否仍旧处于激活状态。推荐debug代码,察看详细错误信息。

8,757

社区成员

发帖
与我相关
我的任务
社区描述
WPF/Silverlight相关讨论
社区管理员
  • WPF/Silverlight社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧