Implement a clock server using UDP

xiaoxiao2021-03-06  41

It is common to implement a clock synchronization on the website. Here is a UDP method to implement one. Which will be called to WINAPIusing 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.Threading ; // Use the thread using system.text; // program to encode

A summary description of Namespace udptimerser {///

/// Form1. /// public class Form1: System.Windows.Forms.Form {private System.Windows.Forms.Label label1; private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.Button button1;

Private udpclient server; private IpendPoint ReceivePoint; private int port = 10000; // Define port number private int = 127001; // Set local IP address private thread startserver; ///

/// Required designer variable . /// private system.componentmodel.container components = null;

Public Form1 () {// // Windows Form Designer Support for // InitializeComponent ();

// // Todo: Add any constructor code after INITIALIZEComponent call //}

///

/// Clean all the resources being used. /// protected override void dispose (Bool Disposing) {Try {// Turns the thread startserver.abort (); // Clear resource server.close ();} catch {}; if (disposing) {ix ( Components! = null) {components.dispose ();}} Base.dispose (Disposing);

}

#REGION Windows Form Designer The code ///

/// designer supports the required method - do not use the code editor to modify the // / this method.

/// private void initializecomponent () {this.listbox1 = new system.windows.forms.listbox (); this.label1 = new system.windows.forms.label (); this.button1 = new system. Windows.Forms.Button (); this.SuspendLayout (); this.listbox1.itemheight = 12; this.listbox1.location = new system.drawing.point (14, 40); this.listbox1.name = "listbox1"; This.listbox1.size = new system.drawing.size (268, 220); this.listbox1.tabindex = 0; this.label1.forecolor = system.drawing.color.red; this.label1.Location = new system.drawing .Point (44, 10); this.label1.name = "label1"; this.label1.size = new system.drawing.size (210, 24); this.Label1.Tabindex = 1; this.label1.text = "UDP timing server is running ..."; this.button1.flatstyle = system.windows.forms.flatstyle.flat; this.button1.location = new system.drawing.point (106, 278); This.button1.name = "button1"; this.button1.size = new system.drawing.size (75, 34); this.button1. Tabindex = 2; this.button1.text = "clear information"; this.button1.click = new system.eventhandler (this.Button1_Click; this.autoscalebasesize = new system.drawing.size (6, 14); this. ClientSize = new System.Drawing.Size (300, 329); this.Controls.AddRange (new System.Windows.Forms.Control [] {this.button1, this.listBox1, this.label1}); this.MaximizeBox = false "This.name =" form1 "; this.text =" UDP pair server side "; this.Load = new system.eventhandler (this.form1_load);

this.ResumeLayout (false);} #ENDREGION

///

/// The primary entry point of the application. /// [stathread] static void main () {Application.run (new form1 ());}

Private void form1_load (Object sender, system.eventargs e) {run ();

/ / Please note: In the following code, the client program is agreed to send the pair request information to the 8080 port number of the server. // The server-side program receives data received to the local 8080 port number to complete the data reception. / / In order to enable the server-side program to know that the client proposes request and to send the timing information to the port number of the client, the // client program is designed for the transmitted request information. The client's timing request information structure is: /// computer name / client receiving information port number ////////////> The port number of receiving server-side time data if the client computer name is: GreyStar, the port number of receiving server-side time data is 1000, / / Then the client program sent by the client program is: GreyStar / 1000. /// The server-side program requests data when the client is received, and after analyzing, // can accurately send the server-side current time and date to the client specified port number through the SEND method of the UDPCLIENT class. on. // This client program can obtain the current time and date of the server side by reading the specified port number, // to correct the time and date of the client.

Public void start_server () {while (true) {// Receive data from the remote host to the local 8080 port data byte [] recdata = server.receive (Reciiencoding Encode = new asciiencoding (); // Get the client Request data string read_str = encode.getstring (recdata); // Extract the client's information, store String [] Temp = Read_Str.Split ("/" / "/"); // Display The request information of the port number listbox1.items.add ("time:" datetime.now. TolongTimeString () "Receive information is as follows:"); listbox1.items.add ("client:" temp [0]); ListBox1.Items.add ("port number:" Temp [1]); // Send server-side time and date byte [] senddata = encode.getbytes ()); ListBox1.items. Add ("Send Server Time!"); // Send Server Time Server.send on the specified port number of the remote host server.send (SendData, SendData.length, Temp [0], INT32.PARSE (Temp [1]));}}

Public void run () {// uses local 8080 port numbers to initialize a UDP network service server = new udpclient (port); ReceivePoint = New IpendPoint (New iPadDress (IP), port); // Open a thread StartServer = New Thread (new ThreadStart (start_server)); // start threads startServer.Start ();} private void button1_Click (object sender, System.EventArgs e) {listBox1.Items.Clear ();}}} using System; using System.Drawing Using system.collections; using system.windows.form; using system.data; using system.net; using system.net.sockets; using system.Runtime.Intericket;

// Client Program Namespace UdptimerClient {///

/// Form1 Summary Description. /// public class Form1: System.Windows.Forms.Form {private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox3; private System.windows.Forms.Button Button1; Private System.windows.Forms.Button Button2; Private System.Windows.Forms.Label Label1; Private System.Windows.Forms.Label Label2;

Private udpclient client; // Create a UDP Network Service Private IpendPoint ReceivePoint; private int port = 8080; // Defines the port number corresponding to the receiving server-side program to send a pair information corresponding to the port number priz, TimeString = DateTime.now.toString (); // Storage Time Date Information String Private DateTime Temp; Private System.Windows.Forms.Label Label3; // Defines a time type to modify the current time and date

///

/// The required designer variable. /// private system.componentmodel.container components = null;

[DLLIMPORT ("kernel32.dll")] private static extern bool setsystemtime (systemtime time);

Public Form1 () {// // Windows Form Designer Support for // InitializeComponent ();

// // Todo: Add any constructor code after INITIALIZEComponent call //}

///

/// Clean all the resources being used. /// Protected Override Void Dispose (Bool Disposing) {if (disponents! = null) {Components.dispose ();}} Base.Dispose (DISPOSION);} #Region Windows Form The code generated by the designer /// /// designer supports the required method - do not use the code editor to modify the // / this method.

/// private () {this.button1 = new system.windows.Forms.Button (); this.button2 = new system.windows.Forms.Button (); this.textbox1 = new system ..TextBox1 = new system. Windows.Forms.TextBox (); this.textbox2 = new system.windows.forms.textbox (); this.label1 = new system.windows.forms.label (); this.label2 = new system.windows.forms.label (); This.label3 = new system.windows.forms.label (); this.textBox3 = new system.windows.forms.textbox (); this.suspendlayout (); // // Button1 // this.button1. Flatstyle = system.windows.forms.flatstyle.flat; this.button1.location = new system.drawing.point (128, 128); this.button1.name = "button1"; this.button1.size = new system.drawing .Size (112, 40); this.button1.tabindex = 0; this.button1.text = "get"; this.button1.click = new system.eventhandler (this.button1_click); // // Button2 // This.button2.flatstyle = system.windows.forms.flatstyle.flat; this.button2.location = new system.drawing.point ( 128, 184); this.button2.name = "button2"; this.button2.size = new system.drawing.size (112, 40); this.button2.tabindex = 1; this.button2.text = " "; This.button2.click = new system.eventhandler (this.button2_click); /// textBox1 // this.textbox1.location = new system.drawing.point (120, 56); this.TextBox1.name = "TextBox1"; this.textbox1.size = new system.drawing.size (200, 21); this.textbox1.tabindex = 2; this.TextBox1.text = ""; /// textbox2 // this.TextBox2. Location = new system.drawing.point (120, 88);

THISTBOX2.NAME = "textbox2"; this.textbox2.size = new system.drawing.size (200, 21); this.textBox2.TabINDEX = 3; this.TextBox2.text = ""; /// Label1 // this.label1.location = new system.drawing.point (48, 56); this.label1.name = "label1"; this.label1.tabindex = 4; this.label1.text = "local time:"; /// Label2 // this.label2.location = new system.drawing.point (40, 88); this.label2.name = "label2"; this.label2.size = new system.drawing.size (88, 24); this.label2.tabindex = 5; this.label2.text = "server time:"; // // label3 // this.label3.Location = new system.drawing.point (16, 24); this. Label3.name = "label3"; this.label3.size = new system.drawing.size (112, 23); this.label3.tabindex = 6; this.label3.text = "Setting server address:"; ///// // textBox3 // this.textBox3.Location = new system.drawing.point (120, 24); this.textbox3.name = "textbox3"; this.TextBox3.size = new system.drawing.size (200, 21) Im.TextBox3.tabindex = 7; this.textbox 3.Text = ""; // // Form1 // this.autoscalebasesize = new system.drawing.size (6, 14); this.clientsize = new system.drawing.size (352, 245); this.Controls. Add (THXTBOX3); this.Controls.add (this.TextBox2); this.Controls.add (this.TextBox1); this.controls.add (this.button2); this.controls.add (this.button1) This.controls.add (this.label1); this.controls.add (this.label2); this.Controls.add (this.label3); this.maximizebox = false; this.name = "form1"; this. TEXT = "UDP timing client";

this.ResumeLayout (false);} #ENDREGION

///

/// The primary entry point of the application. /// [stathread] static void main () {Application.run (new form1 ());}

[StructLayout (LayoutKind.Sequential)] public class SystemTime {public short year; public short Month; public short DayOfWeek; public short Day; public short Hour; public short Minute; public short Second; public short Milliseconds;} // define system time Structure

void Start () {client = new UdpClient (port); IPAddress a = IPAddress.Parse ( "127001"); receivePoint = new IPEndPoint (a, port); IPAddress HostIP; bool continueLoop = true; while (continueLoop) {string hostName = DNS.GETHOSTNAME (); system.text.asciiencoding encode = new system.text.asciiencoding (); // Define the request information sent to the server // Request information is a string, feedback for the client name and receiving server String SENDSTRING = hostname "/" port.toTnow (); byte [] sendData = encode.getbytes; // Decision User input is the IP address or computer name TRY {Hostip = Ipaddress.parse (TextBox3.text);} catch {// If the computer name is entered, follow the code to do the following. // Send request information, the server port is set to 10000 client.send (SendData, SendData) (sendData, senddata); // receive information from the server-side information byte [] recdata = client.receive (Rec ReceivePoint); TIMESTRING = Encode.getstring (recdata); client.close (); Continueloop = false; returno;} // Enter an IP address, then perform the following code iPENDPOINT HOST = New IpendPoint (HostIP, 10000); // Send Request Information Client. Send (SendData, Senddata.length, Host); // Receive information from the server side byte [] recdata1 = client.receive (Ref receivePoint); // Get the time and date of the server side TimeString = Encode.getstring (RecData1); Client. Close (); // Exit loop continueloop = false;}}

Private void button1_click (object sender, system.eventargs e) {start (); textbox1.text = datetime.now.tostring (); // Display client current time and date textBox2.text = TIMESTRING; // Display server Current time And date

}

Private void button2_click (object sender, system.eventargs e) {start (); // Transition the received data transition time date format try {temp = DateTime.Parse (TimeString);} catch {messagebox.show ("error time" ); Return;} // Define the time based on the date, date systemtime st = new systemTIME (); st.Year = (short) TEMP.YEAR; st.month = (short) Temp.month; ST. Dayofweek = (short) Temp.dayofweek; st.day = (short) temp.day; st.Hour = Convert.Toint16 (TEMP.HOUR); if (st.Hour> = 12) {st.Hour- = (SHORT 8;} else if (st.Hour> = 8) {st.HOUR- = (short) 8;} else {st.hour = (short) 16;} st.minute = convert.Toint16 (Temp.minute) St.second = convert.Toint16 (Temp.Second); st.milliseconds = communication.toint16 (Temp.MilliseCond); // Modify the time and date IF of the local end (SetSystemTime (ST)) {MessageBox.show (datetime.now .Tostring (), "modified success");} else messagebox.show ("unsuccessful!", "Unsuccessful");}}}

转载请注明原文地址:https://www.9cbs.com/read-57042.html

New Post(0)