Although the sparrow is small, It is dirty-C # create a windows Service and socket communication instance

Source: Internet
Author: User
Tags mailmessage smtpclient

I have always been a practitioner and believe that learning in practice is the best way to learn. Therefore, when adding an article to a blog, you are always used to writing some specific technical knowledge points. I feel that these things can help developers who learn how to use. net c. Although I am not good at writing, my knowledge is gradually applied. But in the spirit of mutual learning, I hope that I can deepen my understanding while summing up, improve your understanding of each knowledge.

To put it bluntly, what I want to talk about today is a small application that combines the windows service with Soctket, mail sending, and text message sending. I don't have much functionality, but I have a lot of knowledge points in. net. I feel that it is of learning significance to my friends who are initially familiar with this knowledge.

This feature comes from the need for a monitoring Folder:

1. Polling and monitoring the status of files in the folder

2. Notify the Administrator by email or text message after an exception is detected.

3. Use email notification in an Internet environment.

4. If you do not have an Internet connection, you can use a computer with an SMS device to send an SMS reminder.

 

After detailed functional analysis, the function is divided into four small functional units:

1. Use c # To develop windows Services for folder polling and monitoring.

2. reference the mail processing class under the system.net. mail naming control in the. net Framework to send emails.

3. scoket is used in the LAN to solve the communication problem between Short Message devices and monitoring computers in the LAN.

4. C # perform simple and necessary secondary development on SMS devices.

 

1. Implement round robin monitoring for windows Services

Windows Services, formerly NT services, are introduced as part of the Windows NT operating system. You must use an NT-level operating system to run Windows Services, such as Windows NT, Windows 2000 Professional, windows XP, or Windows 2000 Server. For example, products in the form of Windows Services include Microsoft Exchange and SQL Server, and Windows Time services such as computer clock settings. It is started with the Windows operating system and runs in the background. It usually does not interact with users.

In. it is very simple and convenient to create a Windows Service under the. net Framework. It encapsulates the creation and control processes of Windows service programs. The program-related namespaces involve the following two: System. serviceProcess and System. diagnostics.

First, create a windows service. You can directly create a windows Service Project in the. net Framework, and add necessary logical processing to the Service Startup event. [See the code below for implementation 〕

 

 Protected override void OnStart (string [] args)
{
// TODO: Add code here to start the service.
// Read configuration information
ReadConfig ();

Timer1.Elapsed + = new System. Timers. ElapsedEventHandler (timer1_Elapsed );
Timer1.Interval = GlobalInfo. TimeInterval;
Timer1.Start ();
}

Void timerincluelapsed (object sender, System. Timers. ElapsedEventArgs e)
{

DirectoryInfo dirs = new DirectoryInfo (GlobalInfo. DirName );
Int count = 0;
Switch (GlobalInfo. Type)
{
Case 0: // Delay Time
Foreach (FileInfo var in dirs. GetFiles ())
{
DateTime createTime = var. CreationTime;
If (System. DateTime. Now> createTime. AddHours (GlobalInfo. Size ))
Count ++;
}
If (count> 0)
MessageSender. Send (GlobalInfo. Norm> 1? False: true, string. Format ("{0} data files are delayed for more than {1} hours. Please note. [Report time: {2}] ", count. ToString (), GlobalInfo. Size. ToString (), System. DateTime. Now. ToString ()));
Break;
Case 1: // Number of delayed data packets
Count = dirs. GetFiles (). Length;
If (count> GlobalInfo. Count)
MessageSender. Send (GlobalInfo. Norm> 1? False: true, string. Format ("{0} data files are stranded at the same time. Please note. [Report time: {1}] ", count. ToString (), System. DateTime. Now. ToString ()));
Break;
Default:
Break;
}
}

 

 

Ii. Mail sending Function

I mentioned the use of email in a previous article, so I will not elaborate on it. [Code: see below 〕

Static void Send (string titel, string megHtml, string subject) {string meg = ""; // The sender string smtpAuthUsername = GlobalInfo. senderAddr; // the sender's password string smtpAuthPassword = GlobalInfo. senderPwd; // sending Server string smtpServer = GlobalInfo. smtpServer; string objEmail = GlobalInfo. objAddr; // defines the transmission protocol System. net. mail. smtpClient smtp = new System. net. mail. smtpClient (smtpServer); // sets the smtp for the authenticated sender. credentials = new S Ystem. net. networkCredential (smtpAuthUsername, smtpAuthPassword); // the asynchronous sending completes to obtain the sending status smtp. sendCompleted + = new System. net. mail. sendCompletedEventHandler (SendCompletedCallback); try {System. net. mail. mailMessage mail = new System. net. mail. mailMessage (); mail. from = new System. net. mail. mailAddress (smtpAuthUsername, smtpAuthUsername); // reply to the person's name mail. replyTo = new System. net. mail. mailAddress (smtpAuthUsern Ame, smtpAuthUsername); // recipient mail. to. add (objEmail); // mail Priority mail. priority = System. net. mail. mailPriority. normal; // set html mail. isBodyHtml = true; // the title of mail. subject = titel; // content mail. body = megHtml; smtp. send (mail); meg = string. format ("{0} {1} email sent successfully. ", System. DateTime. Now. ToString (), objEmail); WriteLog (meg);} catch {meg = string. Format (" {0} {1} failed to send the email. ", System. DateTime. Now. ToString (), objEmail); WriteLog (meg );}}

3. Socket Communication in LAN

The original intention of Socket is "Socket ". When the application layer uses the transport layer for data communication, TCP and UDP may encounter concurrent services for multiple application processes at the same time. Multiple TCP connections or multiple application processes may need to transmit data through the same TCP port. To differentiate different application processes and connections, many computer operating systems provide interfaces called Sockets for applications to interact with TCP/IP protocols, differentiate network communication and connections between processes of different applications. Generate a socket with three parameters: the destination IP address for communication, the transport layer protocol (TCP or UDP) used, and the port number used. By combining these three parameters and binding them with a "Socket" Socket, the application layer can distinguish communications from processes or network connections of different applications through the Socket interface with the transport layer, implements concurrent data transmission services. The Socket can be seen as an endpoint in the communication connection between two programs. One program writes a piece of information into the Socket, and the Socket sends this information to another Socket, this information can be transmitted to other programs.

Because the current SMS device location and another server in the LAN, you need to send the information to another computer in the LAN in the text message Notification status. A client that receives information is required for socket communication. And the client needs some parameter settings. For example, reception phone number, start-up, communication computer IP address, etc. [For information receiving code, see below 〕

 

Socket socket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); socket. setSocketOption (SocketOptionLevel. socket, SocketOptionName. reuseAddress, 1); try {socket. bind (new IPEndPoint (IPAddress. parse (Info. IP), int. parse (Info. PORT); socket. listen (int) SocketOptionName. maxConnections); while (true) {Socket a = socket. accept (); if (. connected) {byte [] stream = new byte [8 0];. receive (stream); string message = System. text. encoding. UTF8.GetString (stream); InsertRechText ins = new InsertRechText (Insert); Invoke (ins, new object [] {message});} if (isover) return ;}} catch (Exception ex) {WriteLog (string. format ("failed to receive information. [{0}] ", ex. Message); throw ex;} finally {socket. Close ();}

Iv. Secondary Development of SMS Devices

SMS device is a big data warehouse DG-C1A SMS cat. The hardware has a corresponding secondary development class library, which is easy to develop. Directly encapsulate the referenced method into a static method of the class. It can be called directly. (Directly paste the code)

 

[DllImport ("GSMMultiPort. dll ", EntryPoint =" GSMModemInit ", CharSet = CharSet. ansi, CallingConvention = CallingConvention. stdCall)] public static extern bool GSMModemInit (string device, string baudrate, string initstring, string charset, bool swHandshake, string sn); // send Short Message [DllImport ("GSMMultiPort. dll ", EntryPoint =" GSMModemSMSsend ", CharSet = CharSet. ansi, CallingConvention = CallingConvention. stdCall)] public static extern bool GSMModemSMSsend (string device, string serviceCenterAddress, int encodeval, string text, int textlen, string phonenumber, bool requestStatusReport ); // get the error message [DllImport ("GSMMultiPort. dll ", EntryPoint =" GSMModemGetErrorMsg ", CharSet = CharSet. ansi, CallingConvention = CallingConvention. stdCall)] public static extern string GSMModemGetErrorMsg (string device );

 

After the function is completed, the deployment works well. It seems that this function is very small. However, I still feel that I have gained a lot of knowledge. After all, there is a specialization in the industry, and the technology that everyone focuses on in the development of the industry is limited. It is good for you to learn more about each aspect of your knowledge. Haha 〕. Learn together.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.