private void InitSocket()
{
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(IPAddress.Parse(ip), 8099);
AsyncReveive();
}
catch (Exception)
{
MessageBox.Show("失败,尝试重新连接");
ConnectServer = new DispatcherTimer();
ConnectServer.Interval = TimeSpan.FromSeconds(1);
succee = false;
ConnectServer.Tick += (e, f) =>
{
try
{
if (succee == false)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(IPAddress.Parse(ip), 8099);
ConnectServer.Stop();
ConnectServer = null;
succee = true;
}
}
catch (Exception)
{
}
};
ConnectServer.Start();
}
}
private void AsyncReveive()
{
byte[] data = new byte[1024];
try
{
//开始接收消息
socket.BeginReceive(data, 0, data.Length, SocketFlags.None,
IAsyncResult =>
{
try
{
int length = socket.EndReceive(IAsyncResult);
if (length > 0)
{
content = Encoding.UTF8.GetString(data);
content = content.TrimEnd('\0');
this.Dispatcher.BeginInvoke((Action)(() =>
{
InitConent();
}));
AsyncReveive();
}
//else
// dispose();
}
catch (Exception)
{
//进入异常后重新连接
InitSocket();
}
}, null);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}