c# tcp客户端和服务端,断线重连
当然以上客户端的断线 报异常的时候需要重新判断 异常类型,上面是由错误的但是目前是可以实现的。
·
服务端
public class TcpServer
{
private TcpListener _tcpServer = null;
private NetworkStream _stream = null;
private StreamReader _sr = null;
private TcpClient _tcpClient = null;
public Action<string> ReciviMsgAction { get; set; }
private bool isConnected = false;
/// <summary>
/// 开启监听
/// </summary>
public bool StartListener()
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
_tcpServer = new TcpListener(ipAddress, 1233);
_tcpServer.Start();
_tcpClient = _tcpServer.AcceptTcpClient(); //接收挂起的连接请求
isConnected = true;
Task.Run(ReceiveMsg);
Task.Run(CheckIsConntect);
return true;
}
/// <summary>
/// 接收消息
/// </summary>
public void ReceiveMsg()
{
try
{
while (true)
{
if (isConnected)
{
_stream = _tcpClient.GetStream();
_sr = new StreamReader(_stream);
byte[] data = new byte[1024];
int bytesRead = _stream.Read(data, 0, data.Length);
string message = Encoding.ASCII.GetString(data, 0, bytesRead);
ReciviMsgAction.Invoke(message);
Thread.Sleep(1000);
}
}
}
catch (Exception)
{
ReciviMsgAction.Invoke("客户端掉线");
isConnected = false;
}
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="msg"></param>
public void SendMsg(string msg)
{
if (!isConnected)
{
ReciviMsgAction.Invoke("发送失败,客户端掉线");
return;
}
byte[] reply = Encoding.ASCII.GetBytes(msg);
_stream.Write(reply, 0, reply.Length);
}
/// <summary>
/// 检测客户端是都断联
/// </summary>
public void CheckIsConntect()
{
while (true)
{
if (!isConnected)
{
//IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
//_tcpServer = new TcpListener(ipAddress, 1233);
_tcpServer.Start();
_tcpClient = _tcpServer.AcceptTcpClient(); //接收挂起的连接请求
isConnected = true;
ReciviMsgAction.Invoke("客户端重新连接");
Task.Run(ReceiveMsg);
}
Thread.Sleep(1000);
}
}
}
客户端
public class TcpClientServer
{
private IPAddress ipAddress = null;
private TcpClient _client = null;
private NetworkStream _stream = null;
public Action<string> ReciviMsgAction { get; set; }
public TcpClientServer()
{
ipAddress = IPAddress.Parse("127.0.0.1");
_client = new TcpClient();
_client.Connect(ipAddress, 1233);
_stream = _client.GetStream();
Task.Run(ReceiveMsg);
}
/// <summary>
/// 发送
/// </summary>
public void SendMsg(string msg)
{
byte[] data = Encoding.ASCII.GetBytes(msg);
_stream.Write(data, 0, data.Length);
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="msg"></param>
public void ReceiveMsg()
{
try
{
while (true)
{
byte[] data = new byte[1024];
int bytesRead = _stream.Read(data, 0, data.Length);
string message = Encoding.ASCII.GetString(data, 0, bytesRead);
ReciviMsgAction.Invoke(message);
Thread.Sleep(1000);
}
}
catch (Exception ex)
{
ReciviMsgAction.Invoke("服务端关闭");
}
}
}
当然以上客户端的断线 报异常的时候需要重新判断 异常类型,上面是由错误的但是目前是可以实现的。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)