Implement Event Notification-based. Net socket

Source: Internet
Author: User
I have learned MFC before. I have used two classes of csocket and casyncsocket in Winsock packaging. I always think that the function of Event Notification is quite good.
It is useful when the two connected parties do not have certain rules for sending and receiving data. Although it can be implemented without event notification, You Need To cyclically detect the status of the socket or block the wait, if
It is not difficult to do these trivial tasks, so I want to encapsulate these functions. Of course, using delegate and event in. NET is the best choice. The following is my implementation
Some details:
First, let's talk about the idea: in fact, this is still very simple. It is estimated that the experts will not care about it ^_^. When a socket starts to work, such as listening and connection, a thread is started to continuously detect the status of the socket. This event is triggered when the status conditions of an event are met, for details about how to check the socket status, refer.

The functions that may be used for compiling with sockets are as follows: notification of connection success or failure, notification of pending connection on the listening socket, notification of acceptable data, and notification of socket Closure
I have encapsulated the functions above, but I think the last function is of little use ???
My socket class is inherited from system. net. sockets. Socket. The class name tcpeventsocket is implemented as follows:
First, declare the event Delegate type. For details, refer to the code.
Public Delegate void acceptconnectionhandler ();
Public Delegate void connectcompletedhandler (bool connected); // connected indicates that the connection is successful or not.
Public Delegate void datacansendhandler ();
Public Delegate void datacanreceivehandler (INT buffersize); // currently acceptable data volume
Public Delegate void socketclosedhandler ();
What are the specific meanings of these types? We need to declare the corresponding events.
Public event acceptconnectionhandler acceptconnection;
Public event connectcompletedhandler connectcompleted;
Public event datacansendhandler datacansend;
Public event datacanreceivehandler datacanreceive;
Public event socketclosedhandler socketclosed;
In addition, several virtual methods are added to trigger events.
Protected virtual void onacceptconnection ();
Protected virtual void onconnectcompleted (bool connected)
Protected virtual void ondatacansend ()
Protected virtual void ondatacanreceive (INT buffersize)
Protected virtual void onsocketclosed ()
To start the detection thread on an appropriate server, I have rewritten several basic class methods:
New public void listen (INT backlog)
{
Base. Listen (backlog );
Sockstate = socketstate. listenning;
If (! Checkthread. isalive)
Checkthread. Start ();
}
New public void connect (endpoint remoteep)
{
Try
{
Base. Connect (remoteep );
This. Blocking = false; // set the non-blocking status to facilitate the efficiency of Event Notification.
If (! Checkthread. isalive)
Checkthread. Start ();
}
Catch (socketexception)
{
Onconnectcompleted (false );
}
}
The two methods should be called first in actual compilation, so it is appropriate for them to start the detection thread. In addition, the thread must also be suspended when it starts, So I overwrite the close method.
New public void close ()
{
If (checkthread. isalive) // stop the thread before closing the connection
Checkthread. Abort ();
Base. Close ();
Sockstate = socketstate. disconnected;
Onsocketclosed ();
}
So the rest of the work is how to check the socket. The socket class has a select static method, which can detect the status of many sockets. However, you only need to check one, therefore, you can directly use the socket poll method. For more information about poll usage, see msdn. Here I use the code to describe my socket detection method.
While (true) // loop check
{
If (sockstate = socketstate. Disconnected) // if no connection exists currently
{
If (poll (500, selectmode. selectwrite ))
Onconnectcompleted (true); // if it is writable, the connection is successful.
}
Else if (sockstate = socketstate. listenning)
{
If (poll (500, selectmode. selectread) // If the socket is found to have data readable in the listening status, it indicates that someone has been connected and can call accept to accept the connection.
Onacceptconnection ();
}
Else // sockstate = socketstate. Connected
{
If (poll (500, selectmode. selectwrite) // If the write status exists, data can be sent.
Ondatacansend ();
If (poll (500, selectmode. selectread) // if there is a readable state
{
If (available> 0) // if data is readable, you can call receive to accept data.
Ondatacanreceive (available );
Else
{
Onsocketclosed (); // if no data is readable, the connection is closed.
Break;
}
}
}
// Connection fails if no connection is established and an error occurs.
If (sockstate = socketstate. Disconnected & poll (500, selectmode. selecterror ))
Onconnectcompleted (false );
}

Here, the onxxx method is the method for executing event notifications, and the derived classes can overload these methods to directly obtain Event Notifications without the need for a multi-sector Event Notification handler function (similar to
Onaccept and other virtual functions ). However, the corresponding method of the base class is called for the derived function set. Unfortunately, the socket. Accept method has not been rewritten to let it return
Tcpeventsocket, this should be complete, but unfortunately I do not know how to do ^ _ ^, if anyone knows, please advise.

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.