首页 / C# / C# Socket断线重连
C# Socket断线重连
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C# Socket断线重连,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1994字,纯文字阅读大概需要3分钟。
内容图文
![C# Socket断线重连](/upload/InfoBanner/zyjiaocheng/600/04fe87b1387a48199d2d75341e8f672a.jpg)
综合了几篇文章,整理了一个客户端,欢迎小伙伴们提意见
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace TcpLearn
{
class TcpClient
{
private readonly IPEndPoint _serverIpEndPoint;
public TcpClient(string remoteHost, int remotePort)
{
IPAddress serverIpAddress = IPAddress.Parse(remoteHost);
_serverIpEndPoint = new IPEndPoint(serverIpAddress, remotePort);
}
private Socket _socket;
public bool Connect()
{
_socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
_socket.SendTimeout = 1000;
_socket.Connect(_serverIpEndPoint);
// 首次探测时间5 秒, 间隔侦测时间2 秒
byte[] inValue = { 1, 0, 0, 0, 0x88, 0x13, 0, 0, 0xd0, 0x07, 0, 0 };
_socket.IOControl(IOControlCode.KeepAliveValues, inValue, null);
return true;
}
private bool ReConnect()
{
Disconnect();
Connect();
return true;
}
/// <summary>
/// 当socket.connected为false时,进一步确定下当前连接状态
/// </summary>
/// <returns></returns>
private bool IsSocketConnected()
{
bool connectState = true;
bool blockingState = _socket.Blocking;
try
{
byte[] tmp = new byte[1];
_socket.Blocking = false;
_socket.Send(tmp, 1, 0);
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (!e.NativeErrorCode.Equals(10035))
{
connectState = false;
}
}
finally
{
_socket.Blocking = blockingState;
}
return connectState;
}
public string read()
{
//判断是否断开
bool isSocketConnected = IsSocketConnected();
if (!isSocketConnected)
{
//如果断开则进行重启
ReConnect();
return null;
}
string result = string.Empty;
List<byte> data = new List<byte>();
byte[] buffer = new byte[1024];
try
{
var length = 0;
//Receive调用之后会阻塞在这里,等收到数据才会继续向下执行
while ((length = _socket.Receive(buffer)) > 0)
{
for (int j = 0; j < length; j++)
{
data.Add(buffer[j]);
}
if (length < buffer.Length)
{
break;
}
}
}
catch(Exception)
{
ReConnect();
return null;
}
if (data.Count > 0)
{
result = Encoding.ASCII.GetString(data.ToArray(), 0, data.Count);
}
return result;
}
public void Disconnect()
{
_socket.Shutdown(SocketShutdown.Both);
_socket.Disconnect(true);
_socket.Close();
}
}
}
内容总结
以上是互联网集市为您收集整理的C# Socket断线重连全部内容,希望文章能够帮你解决C# Socket断线重连所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。