.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
.net 调度器怎么实现心跳(socket除了他,没选择吧)的更多相关文章
- linux cfs调度器_理论模型
参考资料:<调度器笔记>Kevin.Liu <Linux kernel development> <深入Linux内核架构> version: 2.6.32.9 下 ...
- Yarn 调度器Scheduler详解
理想情况下,我们应用对Yarn资源的请求应该立刻得到满足,但现实情况资源往往是有限的,特别是在一个很繁忙的集群,一个应用资源的请求经常需要等待一段时间才能的到相应的资源.在Yarn中,负责给应用分配资 ...
- 05-k8s调度器、预选策略、优选函数
目录 k8s调度器.预选策略.优选函数 节点选择过程 调度器 预选策略 优选函数 高级调度设置机制 node选择器/node亲和调度 pod亲和性 污点调度 Taints 与 Tolerations ...
- YARN调度器(Scheduler)详解
理想情况下,我们应用对Yarn资源的请求应该立刻得到满足,但现实情况资源往往是有限的,特别是在一个很繁忙的集群,一个应用资源的请求经常需要等待一段时间才能的到相应的资源.在Yarn中,负责给应用分配资 ...
- 监听器初始化Job、JobTracker相应TaskTracker心跳、调度器分配task源码级分析
JobTracker和TaskTracker分别启动之后(JobTracker启动流程源码级分析,TaskTracker启动过程源码级分析),taskTracker会通过心跳与JobTracker通信 ...
- Erlang/OTP 17.0-rc1 新引入的"脏调度器"浅析
最近在做一些和 NIF 有关的事情,看到 OTP 团队发布的 17 rc1 引入了一个新的特性“脏调度器”,为的是解决 NIF 运行时间过长耗死调度器的问题.本文首先简单介绍脏调度器机制的用法,然后简 ...
- CDN调度器HAProxy、Nginx、Varnish
http://www.ttlsa.com/web/the-cdn-scheduler-nginx-haproxy-varnish/ CDN功能如下:1.将全网IP分为若干个IP段组,分组的依据通常是运 ...
- MapReduce多用户任务调度器——容量调度器(Capacity Scheduler)原理和源码研究
前言:为了研究需要,将Capacity Scheduler和Fair Scheduler的原理和代码进行学习,用两篇文章作为记录.如有理解错误之处,欢迎批评指正. 容量调度器(Capacity Sch ...
- yarn的调度器
三种调度器 1.FIFO Scheduler 把应用按提交的顺序排成一个队列,这是一个先进先出队列,在进行资源分配的时候,先给队列中最头上的应用进行分配资源,等最前面的应用需求满足后再给下一个分配,以 ...
随机推荐
- 同IP不同端口Session冲突问题
同IP不同端口Session冲突问题 分类: tomcat2013-09-24 11:19 1146人阅读 评论(0) 收藏 举报 一个服务器上搭建了多个tomcat或者weblogic,端口不一样, ...
- 20145317彭垚 《Java程序设计》第5周学习总结
20145317彭垚 <Java程序设计>第5周学习总结 教材学习内容总结 第八章 8.1 语法与继承架构 package CH5; /** * Created by Administra ...
- mysql安装tcmalloc
TCMalloc(Thread-Caching Malloc)是google-perftools工具中的一个,与标准的glibc库的malloc相比,TCMalloc在内存的分配上效率和速度要高得多, ...
- Aliasing 走样
Computer Science An Overview _J. Glenn Brookshear _11th Edition Have you ever noticed the weird &quo ...
- 获取真实ip的报告
今天登录九秒社团 http://www.9miao.com/的时候忘记了用户名和密码,尝试了5次都没登录成功,网站弹出提示15分钟后才能再次登录.我纳闷它是怎么判断用户的登录次数,这时候用户还没有登录 ...
- Java Phaser
//Listing 6-5. Using a Phaser to Control a One-Shot Action Serving a Variable Number //of Parties im ...
- yii2.0框架中session与cookie的用法
我们在开发项目中南面使用到session给和cookie,那么在yii中有他自己的规则 如下案例: session使用 function actionS1(){ echo $t ...
- Ubuntu+Redis主从配置
软件环境: OS:ubuntu-12.04-desktop-amd64 Redis:redis-2.8.13.tar.gz TCL:tcl8.6.2-src.tar.gz VMware:vmware ...
- 将java.util.Date类型转换成json时,使用JsonValueProcessor将date转换成希望的类型
问题描述: java里面时间类型转换成json数据就成这样了: "createTime":{"date":30,"day":3," ...
- [LeetCode] Sudoku Solver(迭代)
Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...