Clock Synchronization is very common on websites. Here we use UDP to implement one. It will be called to winapi
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. Threading;
// Use the thread in the program
Using system. text;
// Code used in the program
Namespace udptimerserver {
/// <Summary>
/// Summary of form1.
/// </Summary>
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 the port number
Private int IP = 127001;
// Set the local IP Address
Private thread startserver;
/// <Summary>
/// Required designer variables.
/// </Summary>
Private system. componentmodel. Container components = NULL;
Public form1 ()
{
//
// Required for Windows Form Designer support
//
Initializecomponent ();
//
// Todo: add Any constructor code after initializecomponent calls
//
}
/// <Summary>
/// Clear all resources in use.
/// </Summary>
Protected override void dispose (bool disposing)
{
Try
{
// Close the thread
Startserver. Abort ();
// Clear Resources
Server. Close ();
}
Catch
{
};
If (disposing)
{
If (components! = NULL)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
# Region code generated by Windows Form Designer
/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
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 = "When UDP is used, the 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. button#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 peer server ";
This. Load + = new system. eventhandler (this. form#load );
This. resumelayout (false );
}
# Endregion
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main ()
{
Application. Run (New form1 ());
}
Private void form1_load (Object sender, system. eventargs E)
{
Run ();
}
// Note: The following Code specifies the 8080 Port Number of the server when the client sends the request information to the client.
// The server program receives the data sent to the local port number 8080.
// In order to let the server program know that the client initiates a request and sends the peer information to the port number of the client,
// The client program designs the request information at the time of sending. The client-side request information structure is:
//
// Computer name +/+ client receiving information port number
//
// If the client computer name is greystar, the port number for receiving time data from the server is 1000,
// When the client sends a pair, the request data is: greystar/1000.
//
// After the server program receives and analyzes the request data from the client,
// You can use the send method of the udpclient class to accurately send the current time and date of the server to the port number specified by the client.
// In this way, the client can obtain the current time and date of the server by reading the specified port number,
// Modify the time and date of the client.
Public void start_server ()
{
While (true)
{
// Receives data sent from the remote host to the local port 8080.
Byte [] recdata = server. Receive (ref receivepoint );
Asciiencoding encode = new asciiencoding ();
// Obtain client request data
String read_str = encode. getstring (recdata );
// Extract client information and store it in the string array defined as temp
String [] temp = read_str.split ("/". tochararray ());
// Display the request information of the port number
Listbox1.items. Add ("time:" + datetime. Now.
Tolongtimestring () + "received information :");
Listbox1.items. Add ("client:" + temp [0]);
Listbox1.items. Add ("port:" + temp [1]);
// Sending server end time and date
Byte [] senddata = encode. getbytes
(System. datetime. Now. tostring ());
Listbox1.items. Add ("sending server time! ");
// Specify the port number of the remote host to send the server time
Server. Send (senddata, senddata. length,
Temp [0], int32.parse (temp [1]);
}
}
Public void run ()
{
// Use the local 8080 port number 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 the thread
Startserver. Start ();
}
Private void button#click (Object sender, system. eventargs E)
{
Listbox1.items. Clear ();
}
}
}
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. runtime. interopservices;
// Client program
Namespace udptimerclient
{
/// <Summary>
/// Summary of form1.
/// </Summary>
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;
// Define the port number corresponding to the information sent by the receiving server program
Private string timestring = datetime. Now. tostring ();
// String for storing time and date information
Private datetime temp;
Private system. Windows. Forms. Label label3;
// Define a time type to modify the current time and date
/// <Summary>
/// Required designer variables.
/// </Summary>
Private system. componentmodel. Container components = NULL;
[Dllimport ("kernel32.dll")]
Private Static extern bool setsystemtime (systemtime time );
Public form1 ()
{
//
// Required for Windows Form Designer support
//
Initializecomponent ();
//
// Todo: add Any constructor code after initializecomponent calls
//
}
/// <Summary>
/// Clear all resources in use.
/// </Summary>
Protected override void dispose (bool disposing)
{
If (disposing)
{
If (components! = NULL)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
# Region code generated by Windows Form Designer
/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
Private void initializecomponent ()
{
This. button1 = new system. Windows. Forms. Button ();
This. button2 = new system. Windows. Forms. Button ();
This. 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. button#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 );
This. textbox2.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 = "set 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 );
This. textbox3.tabindex = 7;
This. textbox3.text = "";
//
// Form1
//
This. autoscalebasesize = new system. Drawing. Size (6, 14 );
This. clientsize = new system. Drawing. Size (352,245 );
This. Controls. Add (this. textbox3 );
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 = "client when UDP is used ";
This. resumelayout (false );
}
# Endregion
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[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 the 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
// The request information is a string consisting of the client name and the port number of the received server feedback.
String sendstring = hostname + "/" + port. tostring ();
Byte [] senddata = encode. getbytes (sendstring );
// Determine whether the user entered an IP address or a computer name
Try
{
Hostip = IPaddress. parse (textbox3.text );
}
Catch
{
// If the computer name is entered, execute the following code.
// Send request information. The server port is set to 10000.
Client. Send (senddata, senddata.
Length, textbox3.text, 10000 );
// Receives information from the server
Byte [] recdata =
Client. Receive (ref receivepoint );
Timestring = encode. getstring (recdata );
Client. Close ();
Continueloop = false;
Return;
}
// If the IP address is entered, run the following code:
Ipendpoint host = new ipendpoint (hostip, 10000 );
// Send request information
Client. Send (senddata, senddata. length, host );
// Receives information from the server
Byte [] recdata1 = client. Receive (ref receivepoint );
// Obtain the time and date of the server.
Timestring = encode. getstring (recdata1 );
Client. Close ();
// Exit the loop
Continueloop = false;
}
}
Private void button#click (Object sender, system. eventargs E)
{
Start ();
Textbox1.text = datetime. Now. tostring ();
// Display the current time and date of the Client
Textbox2.text = timestring;
// Display the current server time and date
}
Private void button2_click (Object sender, system. eventargs E)
{
Start ();
// Convert the received data to the date format
Try
{
Temp = datetime. parse (timestring );
}
Catch
{
MessageBox. Show ("error time ");
Return;
}
// Define the time and date based on the obtained time and 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 = convert. toint16 (temp. millisecond );
// Modify the local end time and date
If (setsystemtime (ST ))
{
MessageBox. Show (datetime. Now. tostring (), "modified successfully ");
}
Else
MessageBox. Show ("No! "," Unsuccessful ");
}
}
}