
正文
.net 调度器怎么实现心跳(socket除了他,没选择吧)
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
自己写调度器,就要从tcp通信入手;心跳的实现除了使用socket,想不到其他任何方案。
socket基本使用demo:
- Socket Client:
static void Main(string[] args)
{
Socket c; //int port = 4029;
// 避免使用127.0.0.1,我在本机测试是不能运行的
//string host = "127.0.0.1";
//IPAddress ip = IPAddress.Parse(host);
//IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
string ip = string.Empty;
System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
for (int i = ; i != IpEntry.AddressList.Length; i++)
{
if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
{
ip = IpEntry.AddressList[i].ToString();
}
}
IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(ip), ); c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket try
{
c.Connect(ipend);//连接到服务器 Console.WriteLine("连接到Socket服务端..."); Console.WriteLine("发送消息到服务端...");
string sendStr = "m s g";
byte[] bs = Encoding.Default.GetBytes(sendStr);
c.Send(bs, bs.Length, ); string recvStr = "";
byte[] recvBytes = new byte[];
int bytes;
bytes = c.Receive(recvBytes, recvBytes.Length, );//从服务器端接受返回信息
recvStr += Encoding.Default.GetString(recvBytes, , bytes); Console.WriteLine("服务器返回信息:" + recvStr);
}
catch (ArgumentNullException ex1)
{
Console.WriteLine("ArgumentNullException:{0}", ex1);
}
catch (SocketException ex2)
{
Console.WriteLine("SocketException:{0}", ex2);
}
//string ip = string.Empty;
//System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
//for (int i = 0; i != IpEntry.AddressList.Length; i++)
//{
// if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
// {
// ip = IpEntry.AddressList[i].ToString();
// }
//}
//IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(ip), 8889);
//Socket sc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//sc.Connect(ipend);
//string message = "请升级软件";
//byte[] bt = Encoding.GetEncoding("gb2312").GetBytes(message);
//sc.Send(bt, bt.Length, 0);
//byte[] rebuff = new byte[1024];
//int recive = sc.Receive(rebuff, rebuff.Length, 0);
//string returnval = "";
//returnval += Encoding.GetEncoding("gb2312").GetString(rebuff, 0, recive); sc.Close();
//Console.WriteLine(returnval); Console.ReadKey();
}
- Socket Server:
class Program
{
static SocketListener listener; public static void Main(string[] args)
{
System.Timers.Timer t = new System.Timers.Timer();
//实例化Timer类,设置间隔时间为5000毫秒;
t.Elapsed += new System.Timers.ElapsedEventHandler(CheckListen);
//到达时间的时候执行事件;
t.AutoReset = true;
t.Start(); listener = new SocketListener();
listener.ReceiveTextEvent += new SocketListener.ReceiveTextHandler(ShowText);
listener.StartListen(); // 客户最近提出一个需求,要在WEB上远程管理客户端软件。那我们就仿路由器那种模式用SOCKET来解决吧。做了个DEMO,本机测试OK,拿到别的机器上做服务器,
//提示由于目标机器积极拒绝,无法连接。查询各种资料,有的说是端口没开,有的说是服务没开。各种雾水啊!仔细一想,问题可能出在本机在局域网IP上,
//而不是用127.0.0.1。更正代码后,问题解决。下面演示服务器端代码的关键部分。
//string ip = "";
//System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
//for (int i = 0; i != IpEntry.AddressList.Length; i++)
//{
// if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
// {
// ip = IpEntry.AddressList[i].ToString();
// }
//} //IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(ip), 8889);
//Socket sc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//sc.Bind(ipend); //Socket acc; //while (true)
//{
// sc.Listen(1);
// acc = sc.Accept();
// byte[] buff = new byte[1024];
// int recbyte = acc.Receive(buff, buff.Length, 0);
// if (recbyte == 0)
// break;
// string reciveval = "";
// reciveval += Encoding.Default.GetString(buff, 0, recbyte); // Console.WriteLine(reciveval);
// string returnValue = "Accepted";
// byte[] returnBy = Encoding.Default.GetBytes(returnValue);
// acc.Send(returnBy, returnBy.Length, 0);
//} //acc.Close();
//sc.Close(); Console.ReadKey();
} private static void ShowText(string text)
{
Console.WriteLine(text);
} private static void CheckListen(object sender, System.Timers.ElapsedEventArgs e)
{
if (listener != null && listener.Connection != null)
{
Console.WriteLine("连接数:" + listener.Connection.Count.ToString());
}
}
} public class Connection
{
Socket _connection; public Connection(Socket socket)
{
_connection = socket;
} public void WaitForSendData()
{
try
{
while (true)
{
byte[] bytes = new byte[];
string data = ""; //等待接收消息
int bytesRec = this._connection.Receive(bytes); if (bytesRec == )
{
// ReceiveText("客户端[" + _connection.RemoteEndPoint.ToString() + "]连接关闭...");
break;
} data += Encoding.UTF8.GetString(bytes, , bytesRec);
ReceiveText("收到消息:" + data); string sendStr = "服务端已经收到信息!";
byte[] bs = Encoding.UTF8.GetBytes(sendStr);
_connection.Send(bs, bs.Length, );
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
} public delegate void ReceiveTextHandler(string text);
public event ReceiveTextHandler ReceiveTextEvent;
private void ReceiveText(string text)
{
if (ReceiveTextEvent != null)
{
ReceiveTextEvent(text);
}
}
} public class SocketListener
{
public Hashtable Connection = new Hashtable(); public void StartListen()
{
Agine:
try
{
//端口号、IP地址
//int port = 8889;
//string host = "127.0.0.1";
//IPAddress ip = IPAddress.Parse(host);
//IPEndPoint ipe = new IPEndPoint(ip, port);
string ip = string.Empty;
System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
for (int i = ; i != IpEntry.AddressList.Length; i++)
{
if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
{
ip = IpEntry.AddressList[i].ToString();
}
}
IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(ip), );
//创建一个Socket类
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(ipend);//绑定2000端口
s.Listen();//开始监听 ReceiveText("启动Socket监听..."); while (true)
{
Socket connectionSocket = s.Accept();//为新建连接创建新的Socket ReceiveText("客户端[" + connectionSocket.RemoteEndPoint.ToString() + "]连接已建立..."); Connection gpsCn = new Connection(connectionSocket);
gpsCn.ReceiveTextEvent += new Connection.ReceiveTextHandler(ReceiveText); Connection.Add(connectionSocket.RemoteEndPoint.ToString(), gpsCn); //在新线程中启动新的socket连接,每个socket等待,并保持连接
Thread thread = new Thread(new ThreadStart(gpsCn.WaitForSendData));
thread.Name = connectionSocket.RemoteEndPoint.ToString();
thread.Start();
}
}
catch (ArgumentNullException ex1)
{
ReceiveText("ArgumentNullException:" + ex1);
}
catch (SocketException ex2)
{
ReceiveText("SocketException:" + ex2);
} goto Agine;
} public delegate void ReceiveTextHandler(string text);
public event ReceiveTextHandler ReceiveTextEvent;
private void ReceiveText(string text)
{
if (ReceiveTextEvent != null)
{
ReceiveTextEvent(text);
}
}
}
代码实现参考:http://blog.bossma.cn/csharp/csharp_socket_example/
https://msdn.microsoft.com/zh-cn/library/System.Net.Sockets.Socket(v=vs.100).aspx








