Reprint: http://www.cnblogs.com/networkcomms/p/4304362.html
SOURCE download
In CS programs, the disconnection should be a common feature.
Here the disconnection is mainly refers to the server side because of some kind of failure, the server-side program or the system has been restarted, the client can automatically detect the server-side drop, and try to reconnect
This program is based on the Networkcomms (2.3.1 version) of the Open source C # Communication framework from the UK
First look at the effect
Initial state:
When the server-side program shuts down, the client automatically detects and displays the relevant information on the client
Then, we set to re-connect every 5 seconds, you can customize the number of times to re-connect, such as to re-connect 50 times, if not re-connected successfully, then discard the re-connect
Then we restart the server side and the client will show that the reconnect was successful.
The steps are as follows:
You need to modify the code in several NetworkComms2.3.1 communication frameworks
First step: Modify the Noteconnectionshutdown method of the ConnectionInfo class
The method turns out to be:
void Noteconnectionshutdown () { lock (internallocker) connectionstate = Connectionstate.shutdown; }
View Code
Modified to:
PrivateBOOL Reconnectflag =False;///<summary>///Whether to reconnect mode///</summary>PublicboolReconnectflag {get {ReturnReconnectflag; }set {Reconnectflag =Value } }///<summary>///Note this connection as shutdown///</summary>Internalvoid Noteconnectionshutdown () {lock (Internallocker) connectionstate = Connectionstate.shutdown; //if (Reconnectflag = Span style= "color: #0000ff;" >false) {Statechanged.raise (this, new Stringeventargs ( connection exception occurred "// add state Change event public Span style= "color: #0000ff;" >event eventhandler<stringeventargs> statechanged;
Step two: Add the relevant code to the Networkcomms library class as follows:
UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Text;UsingNetworkcommsdotnet.tools;Namespacenetworkcommsdotnet{PublicStaticClassExtensions {PublicStaticvoid Raise<t> (This eventhandler<t> handler,object sender, T args)whereT:eventargs {if (Handler! =Null) handler (sender, args); } }Publicclass Stringeventargs:eventargs {public Stringeventargs (string text) {text = text; } public string Text {setnamespace system.runtime.compilerservices{[ AttributeUsage (AttributeTargets.Method | AttributeTargets.Class | attributetargets.assembly)] sealed class Extensionattribute:attribute {}} Related Code
Step Three: Add the following method to the Networkcomms static class:
void Cleardic () { lock (globaldictanddelegatelocker) {allconnectionsbyid.clear (); Allconnectionsbyendpoint.clear (); Oldnetworkidentifiertoconnectioninfo.clear (); } }
If you are using the V3 version, the code changes slightly:
void Cleardic () { lock (globaldictanddelegatelocker) {allconnectionsbyidentifier.clear (); Allconnectionsbyendpoint.clear (); Oldnetworkidentifiertoconnectioninfo.clear (); } }
V3
Client code:
UsingSystem;UsingSystem.Collections.Generic;UsingSystem.ComponentModel;UsingSystem.Data;UsingSystem.Drawing;UsingSystem.Text;UsingSystem.Windows.Forms;UsingNetworkcommsdotnet;UsingDpsbase;UsingSystem.Net;UsingSystem.Threading;Namespaceappclient{PublicPartialClassForm1:form {//Connection Information classPublic ConnectionInfo Connnectioninfo =Null;//Connection classConnection Connection;PublicForm1 () {InitializeComponent ();}//Display new information on a formvoid Form_connectionstatusnotify (Objectsender, Stringeventargs e) {if (This. invokerequired) {This. Invoke (New Eventhandler<stringeventargs> (This. form_connectionstatusnotify), sender, E); }Else{Lbllink.text =E.text; Lbllink.forecolor =Color.Blue; } }PrivateBOOL Servernotifyclose =False;PublicEvent eventhandler<stringeventargs>connectionstatusnotify;void Connnectioninfo_statechanged (Objectsender, Stringeventargs e) {//If the server notification is not turned off, the automatic re-connection is not processed if the server notification is turned off//Servernotifyclose is not used in this demoif (Servernotifyclose = =False) {//Update connection information class settings for re-connect mode Connnectioninfo.reconnectflag =True; Connectionstatusnotify.raise (ThisNew Stringeventargs ("The connection to the server has been disconnected due to server failure"));int num =0;int retrycount =30;int retryspaninmsecs =5000;Do{Try{networkcomms.cleardic (); connection =Tcpconnection.getconnection (Connnectioninfo); Connectionstatusnotify.raise (ThisNew Stringeventargs ("Re-connected success")); Connnectioninfo.reconnectflag =False;Break; }Catch(Exception ex) {num++;if (Num <RetryCount) {connectionstatusnotify.raise (ThisNew Stringeventargs ("is working on the first"+ num +"Secondary re-connect")); Thread.Sleep (RETRYSPANINMSECS); } } }while (Num <RetryCount); } }Privatevoid Button1_Click (Objectsender, EventArgs e) {connnectioninfo =New ConnectionInfo (Txtip.text,Int. Parse (Txtport.text));//If not successful, the exception message pops up connection =Tcpconnection.getconnection (Connnectioninfo); Button1. Enabled =False; Button1. Text ="Connection Successful";//Connection status change events in the subscription connection information class Connnectioninfo.statechanged + =New eventhandler<stringeventargs>(connnectioninfo_statechanged);This. Connectionstatusnotify + =New eventhandler<stringeventargs>(form_connectionstatusnotify); }//Get fruit-related informationPrivatevoid Button2_Click (Objectsender, EventArgs e) {if (Listbox1.selectedindex >-1) {String resmsg = connection. sendreceiveobject<String> ("Reqfruitengname", "resfruitengname", Span style= "color: #800080;" >5000 " The English name of the fruit you have selected is: "+ resmsg);} else {MessageBox.Show ( " Please select a " ); }} private void form1_formclosing (object sender, FormClosingEventArgs e) {this. Dispose (); } }} Client Code
No additional settings are required on the server side.
TCP communication-based client wire break and heavy connection