Implement event-based notifications. NET sockets

Source: Internet
Author: User
Tags bool implement connect readable socket thread
Previously learned MFC, I used it inside the packaging Winsock two classes CSocket and CAsyncSocket, I have always felt it which event notification function is relatively good, especially in the connection between the two parties to send and receive data does not have a certain regularity when more useful, Although it is also possible to implement functionality without its event notification, you need to loop through the socket to check the status or block the wait, and if you have to do these trivial tasks every time, it's a hassle, so I want to encapsulate these features once. Of course, using delegate and event in. NET is the best choice. Here are some of the details I've achieved:

First talk about the idea: In fact, this is still very simple, it is estimated that the experts will be dismissive of the ^_^. When the socket began to work, such as Start listening, start the connection, start a thread to detect the state of the socket, when the condition of a certain event to trigger this event, to know the specific detection of the socket state of the method, please look down.

Commonly used when the socket into the function that may need to use is: connection success or failure of the notification, in the listening socket, there is a pending connection notification, there are data can be accepted notification, socket shutdown notification, there are sockets can send data notification, and so on, I also make the above several functions are encapsulated, But I think the last feature is not very useful???

My socket class is inherited from System.Net.Sockets.Socket, class name Tcpeventsocket, implemented as follows:

Declare the delegate type of the event first, see the code

public delegate void Acceptconnectionhandler ();

public delegate void Connectcompletedhandler (bool connected); Connected indicates whether the connection is successful or not

public delegate void Datacansendhandler ();

public delegate void Datacanreceivehandler (int buffersize); The amount of data currently acceptable

public delegate void Socketclosedhandler ();

These types of specific what meaning should be able to see it, and also to affirm the corresponding event

public event Acceptconnectionhandler Acceptconnection;

public event Connectcompletedhandler connectcompleted;

public event Datacansendhandler Datacansend;

public event Datacanreceivehandler Datacanreceive;

public event Socketclosedhandler socketclosed;

Plus a few virtual methods, which are used 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 in the appropriate Hing, I rewrote several methods of the base class:

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 non-blocking state so that event notification is efficient

if (!checkthread.isalive)

Checkthread.start ();

}

catch (SocketException)

{

Onconnectcompleted (FALSE);

}

}

Both of these methods should be invoked first, so it is appropriate for them to start the detection thread, and the other thread will have to abort, so I rewrite the Close method

New public void Close ()

{

if (checkthread.isalive)//Abort the thread before closing the connection

Checkthread.abort ();

Base. Close ();

Sockstate = socketstate.disconnected;

Onsocketclosed ();

}

So the rest of the work is how to detect sockets, the socket class has a select static method, it can detect many sockets state, but here only need to detect a, so directly with the socket poll method, poll specific use can see MSDN, I'm here to use code to explain how I detect sockets.

while (true)//loop check

{

if (sockstate = = socketstate.disconnected)//If no connection is currently present

{

if (Poll (Selectmode.selectwrite))

Onconnectcompleted (TRUE); If a writable state, the connection succeeds

}

else if (sockstate = = socketstate.listenning)

{

if (Poll, selectmode.selectread))//If a socket has data readable in the listening state, it means that someone is already connected to call accept accept the connection

Onacceptconnection ();

}

else//here Sockstate = socketstate.connected

{

if (Poll (selectmode.selectwrite))////If writable, it means that data can be sent

Ondatacansend ();

if (Poll (selectmode.selectread))//If there is a readable state

{

if (Available > 0)//If there is data readable representation can invoke receive acceptance data

Ondatacanreceive (Available);

Else

{

Onsocketclosed (); No data to read indicates that the connection has been closed

Break

}

}

}

If there is no connection and there is an error state, the connection fails

if (sockstate = = socketstate.disconnected && Poll (selectmode.selecterror))

Onconnectcompleted (FALSE);

}

The OnXxx method here is the method of executing event notifications, and the derived classes can overload these methods to obtain event notifications directly without the need to suspend the event notification handler functions (similar to MFC's onaccept and other virtual functions). However, the corresponding method for invoking the base class of the derived set of functions oh. Unfortunately did not rewrite the Socket.accept method, let it return a tcpeventsocket, this should be more complete, but unfortunately I do not know how to do ^_^, if anyone knows the words welcome advice.

Event notification Mechanism has been basically completed, the lack of only a large number of tests (I did a few of the simplest test, ashamed!!) ^_^)

If you have any questions, please contact yzx110@bit.edu.cn.


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.