⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serverform.cs

📁 实现多个机器间心跳信息的同步访问处理,适用于主从计算环境下的信息传递处理.
💻 CS
字号:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace HeartbeatServer
{
	/// <summary>
	/// The ServerForm contains the Functions for receiving and observing
	/// the Heartbeat via UDP local.
	/// </summary>
	public class ServerForm : System.Windows.Forms.Form
	{
		private System.ComponentModel.Container components = null;

		private System.Windows.Forms.Label lblError;

		private DateTime lastUpdate;
		private Socket udpServerSocket;
		private EndPoint ep = new IPEndPoint(IPAddress.Any, 10000);
		private System.Timers.Timer checkTimer = new System.Timers.Timer();
		private byte[] buffer = new byte[1024];

		/// <summary>
		/// Constructor. Initializes the Form, the Socket and the Timer
		/// </summary>
		public ServerForm()
		{
			InitializeComponent();

			udpServerSocket = new Socket(AddressFamily.InterNetwork,
				SocketType.Dgram, ProtocolType.Udp);
			udpServerSocket.Bind(ep);
			udpServerSocket.BeginReceiveFrom(buffer, 0, 1024, SocketFlags.None, ref ep, new AsyncCallback(ReceiveData), udpServerSocket);
		
			checkTimer.Interval = 1000;
			checkTimer.AutoReset = true;
			checkTimer.Elapsed += new System.Timers.ElapsedEventHandler(checkTimer_Elapsed);
			checkTimer.Start();
		}

		/// <summary>
		/// Dispose used Ressources.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Vom Windows Form-Designer generierter Code
		/// <summary>
		/// Erforderliche Methode f黵 die Designerunterst黷zung. 
		/// Der Inhalt der Methode darf nicht mit dem Code-Editor ge鋘dert werden.
		/// </summary>
		private void InitializeComponent()
		{
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ServerForm));
			this.lblError = new System.Windows.Forms.Label();
			this.SuspendLayout();
			// 
			// lblError
			// 
			this.lblError.Location = new System.Drawing.Point(8, 24);
			this.lblError.Name = "lblError";
			this.lblError.Size = new System.Drawing.Size(280, 16);
			this.lblError.TabIndex = 0;
			// 
			// ServerForm
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
			this.ClientSize = new System.Drawing.Size(292, 48);
			this.Controls.Add(this.lblError);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Name = "ServerForm";
			this.Text = "ServerForm";
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// Main function of this Application. Creates the Form.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new ServerForm());
		}

		/// <summary>
		/// Callback function for the BeginReceiveFrom Function.
		/// Receives the data from the buffer, sets the lastUpdate Variable
		/// and starts a new BeginReceiveFrom.
		/// </summary>
		/// <param name="iar">The result of the asynchronous operation.</param>
		void ReceiveData(IAsyncResult iar)
		{
			// Create temporary remote end Point
			IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
			EndPoint tempRemoteEP = (EndPoint)sender;

			// Get the Socket
			Socket remote = (Socket)iar.AsyncState;

			// Call EndReceiveFrom to get the received Data
			int recv = remote.EndReceiveFrom(iar, ref tempRemoteEP);

			// Get the Data from the buffer to a string
			string stringData = Encoding.ASCII.GetString(buffer,0,recv);
			Console.WriteLine(stringData);
			
			// update Timestamp
			lastUpdate = DateTime.Now.ToUniversalTime();

			// Restart receiving
			if(!this.IsDisposed)
			{
				udpServerSocket.BeginReceiveFrom(buffer, 0, 1024, SocketFlags.None, ref ep, new AsyncCallback(ReceiveData), udpServerSocket);
			}
		}

		/// <summary>
		/// Timer event handler. Checks if the last Heartbeat was more than 3 seconds
		/// ago and sets the lable to the Alarm message.
		/// </summary>
		/// <param name="sender">Sender of the Event; not used.</param>
		/// <param name="e">Parameter for the Event; not used.</param>
		private void checkTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
		{
			// Calculate the Timespan since the Last Update from the Client.
			TimeSpan timeSinceLastHeartbeat = DateTime.Now.ToUniversalTime() - lastUpdate;

			// Set Lable Text depending of the Timespan
			if(timeSinceLastHeartbeat > TimeSpan.FromSeconds(3))
			{
				lblError.Text = "No Answer from ClientForm";
				lblError.BackColor = Color.Red;
			}
			else
			{
				lblError.Text = "ClientForm OK";
				lblError.BackColor = Color.Green;
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -