Asynchronous Socket Communication Summary

xiaoxiao2021-03-06  15

The basic programming points and steps of the socket have been posted, and the code about the asynchronous socket communication is continued here.

Service (asynchronous):

Using system.net;

Using system.net.sockets;

Using system.io;

Using system.text;

Using system.threading;

Public Static ManualReveTevent Alldone = New ManualReveTevent (false);

Private thread th;

PRIVATE BOOL Listenerrun = True;

Socket Listener;

Private const Int max_socket = 10;

Protected Override Void Dispose (Bool Disposing)

{

Try

{

Listenerrun = false;

Th.abort ();

TH = NULL;

Listener.close ();

}

Catch {}

}

// Get the native IP address

// Get the native IP address

Public static ipaddress getServerip ()

{

IPHOSTENTRY IEH = DNS.GETHOSTBYNAME (DNS.GETHOSTNAME ());

Return IEh.AddressList [0];

}

// Listening method

Private void listen ()

{

Try

{

Int nport = int.parse (this.txtLocalport.Text);

Ipaddress serverip = get Serverip ();

IpendPoint IEP = New IpendPoint (ServerIP, NPORT);

Listener = New Socket (AddressFamily.internetwork, sockettype.stream, protocoltype.tcp);

Listener.bind (IEP);

Listener.listen (10);

Statusbar1.panels [0] .text = "port:" this.txtLocalport.text "is listening ...";

While (Listenerrun)

{

Alldone.reset ();

Listener.BeginAccept (new asyncCallback, listener);

Alldone.waitone ();

}

}

Catch (System.Security.securityException)

{

MessageBox.show ("Firewall Security Error!", "Error", MessageBoxButtons.ok, MessageBoxicon.exclamation;

}

}

// Asynchronous callback function

Public Void AcceptCallback (IASYNCRESULT AR)

{

Socket Listener = (socket) ar.asyncstate;

Socket Client = Listener.ndAccept (ar);

alldone.set ();

StateObject State = new stateObject ();

State.worksocket = client;

// remote information

Endpoint tempRemoteep = Client.RemoteEndPoint;

IpendPoint Tempremoteip = (ipendPoint) TempRemoteep; string remote = tempREMOTEIP.Address.tostring ();

String remoport = TempRemoteip.port.toString ();

IPHOSTENTRY HOST = DNS.GETOSTBYADDRESS (TempRemoteip.address);

String hostname = host.hostname;

Statusbar1.panels [1] .text = "Accept [" Hostname "]" RemPip ":" Remoport "Remote Computer is correctly connected!";

THISTBOXREMOHOST.ITEMS.ADD ("[" Hostname "]" Rempip ":" Remoport);

Client.BeginReceive (state.buffer, 0, stateObject.buffearsize, 0,

New asyncCallback (READCALLBACK), STATE);

}

// Asynchronously receive the backup function

Public Void ReadCallback (IasyncResult Ar)

{

StateObject State = (stateObject) ar.asyncState;

Socket Handler = State.Worksocket;

INT BYTESREAD = Handler.Endreceive (ar);

IF (BytesRead> 0)

{

String strmsg = encoding.ascii.getstring (state.buffer, 0, bytesread);

State.sb.append (strmsg);

String content = state.sb.tostring ();

// remote information

Endpoint tempRemoteep = handler.remoteEndpoint;

IpendPoint TempRemoteip = (ipendPoint) TempRemoteep;

String remoteip = tempRemoteip.address.tostring ();

String remoport = TempRemoteip.port.toString ();

IPHOSTENTRY HOST = DNS.GETOSTBYADDRESS (TempRemoteip.address);

String hostname = host.hostname;

Statusbar1.Panels [1] .text = "Information is receiving [" Hostname "]" Rempip ":" Remoport "...";

String time = datetime.now.tostring ();

ListBoxRecv.Items.add ("(" Time ")" Hostname ":");

ListBoxRecv.Items.Add (strmsg);

IF (Content.indexof ("/ x99 / x99")> -1)

{

Statusbar1.Panels [1] .text = "Information is completed!"; //

// Receive complete information

// MessageBox.show ("Receive:" Content);

String msg = powerd.codeparse (content);

Send (Handler, MSG); // Send

// send (content); // Send with separate Socket

}

Else

{

Handler.BeginReceive (state.buffer, 0, stateObject.buffearsize, 0,

New asyncCallback (READCALLBACK), STATE);

}

}

}

// Send

Private Void Send (Socket Handler, String Data)

{

Byte [] Bytedata = Encoding.ASCII.GetBytes (data);

Handler.beginsend (Bytedata, 0, Bytedata.length, 0,

New asyncCallback (SendCallback), Handler;

// Handler.send (ByTedata);

}

#Region // Send with separate Socket

Private Void Send (String Data)

{

// String ip = this.txtremoip.text;

// String port = this.txtremoport.text;

// ipaddress serverip = ipaddress.parse (IP);

// int serverport = convert.toint32 (port);

// IpendPoint IEP = New IpendPoint (ServerIP, Serverport);

// socket socket = new socket (addressfamily.internetwork, sockettype.stream, protocoltype.tcp);

// Socket.connect (IEP);

// Byte [] BYTEMESSAGE = Encoding.ascii.getbytes (DATA);

// socket.send (byteMessage);

// socket.shutdown (socketshutdown.both);

// socket.close ();

}

#ndregion

// Send a callback function asynchronous

// Send a callback function asynchronous

Private Static Void SendCallback (IasyncResult Ar)

{

Try

{

Socket Handler = (socket) ar.asyncState;

INT bytessent = handler.endsend (ar);

Messagebox.show ("Send Success!");

Handler.shutdown (socketshutdown.both);

Handler.close ();

}

Catch (Exception EX)

{

Messagebox.show (ex.totring ());

}

}

Private void btnlisten_click (object sender, system.eventargs e) {

TH = New Thread (New ThreadStart (Listen)); // Initialize the thread in the Listen process

Th.Start (); // Start this thread

this.btnlisten.enabled = false;

}

Private void btnclosenet_click (Object Sender, System.EventArgs E)

{

Try

{

Listenerrun = false;

Th.abort ();

TH = NULL;

Listener.close ();

Statusbar1.panels [0] .text = "is disconnected from the client!";

Statusbar1.Panels [1] .text = "";

}

Catch

{

Messagebox.show ("Connection has not been established, disconnected!", "Warning");

}

}

Private void btnexit_click (Object Sender, System.Eventargs E)

{

Try

{

Listenerrun = false;

Th.abort ();

TH = NULL;

Listener.close ();

Statusbar1.panels [0] .text = "is disconnected from the client!";

Statusbar1.Panels [1] .text = "";

}

Catch (Exception EX)

{

Messagebox.show (ex.Message);

}

Finally

{

Application.exit ();

}

}

// Status object to asynchronously

Public Class StateObject

{

Public Socket Worksocket = NULL;

Public const Int buffersize = 1024;

Public Byte [] buffer = new byte [buffersize];

Public StringBuilder SB = new stringbuilder ();

}

Client (synchronously send and receive):

Using system.net;

Using system.net.sockets;

Using system.io;

Using system.text;

Using system.threading;

Socket socket;

Int numByte = 1024; // number of bytes received at a time

Private void btnconnect_click (Object Sender, System.Eventargs E)

{

Try

{

String ip = this.txtremoip.text;

String port = this.txtremoport.text;

Ipaddress serverip = ipaddress.parse (IP);

INT ServerPort = Convert.Toint32 (Port);

IpendPoint IEP = New IpendPoint (ServerIP, Serverport);

IPHOSTENTRY HOST = DNS.GETOSTBYADDRESS (IEP.ADDRESS);

String hostname = host.hostname;

Socket = new socket (addressfamily.internetwork, sockettype.stream, protocoltype.tcp); socket.connect (IEP);

IpendPoint TempRemoteip = (ipendPoint) socket.localendpoint;

Statusbar1.Panels [0] .text = "port:" TempRemoteip.port.toString () "Listening ...";

Statusbar1.Panels [1] .text = "with remote computer [" Hostname "]" IP ":" port "to establish a connection!";

}

Catch

{

Statusbar1.panels [0] .Text = "Unable to connect to the target computer!";

}

#REGION

// ByteMessage = Encoding.ascii.getbytes (TextBox1.text "99");

// socket.send (byteMessage);

// Byte [] bytes = new byte [1024];

// Socket.Receive (bytes);

// String str = encoding.default.getstring (bytes);

// MessageBox.show ("Receive:" Str);

// socket.shutdown (socketshutdown.both);

// socket.close ();

#ndregion

}

Private void btnsend_click (Object Sender, System.Eventargs E)

{

Try

{

STATUSBAR1.PANELS [1] .text = "is sending information!";

String message = this.txtsend.text;

Sendinfo (MESSAGE);

}

CatCH // abnormal processing

{

Statusbar1.panels [0] .text = "Unable to send information to the target computer!"

}

}

Private void sendinfo (String Message)

{

#REGION

// String ip = this.txtip.text;

// String port = this.txtport.text;

//

// ipaddress serverip = ipaddress.parse (IP);

// int serverport = convert.toint32 (port);

// IpendPoint IEP = New IpendPoint (ServerIP, Serverport);

// Byte [] bytementage;

//

// Socket = New socket (addressfamily.internetwork, sockettype.stream, protocoltype.tcp);

// Socket.connect (IEP); # endregion

Byte [] bytemessage = encoding.ascii.getbytes (Message "/ x99 / x99);

Socket.send (ByteMessage);

// remote information

Endpoint tempRemoteep = Socket.RemoteEndPoint;

IpendPoint TempRemoteip = (ipendPoint) TempRemoteep;

String remoteip = tempRemoteip.address.tostring ();

String remoport = TempRemoteip.port.toString ();

IPHOSTENTRY HOST = DNS.GETOSTBYADDRESS (TempRemoteip.address);

String hostname = host.hostname;

//send Message

String Time1 = DateTime.now.toString ();

ListBoxSend.Items.Add ("( Time1 ") " Hostname ": ");

ListBoxSend.Items.Add (Message);

// is sent, directly receive

Stringbuilder SB = New StringBuilder ();

While (True)

{

Statusbar1.Panels [1] .text = "Waiting for receiving information ...";

Byte [] bytes = new byte [Numbyte];

INT recbytes = socket.receive (bytes);

String strmsg = encoding.default.getstring (bytes);

String time2 = datetime.now.toString ();

ListBoxRecv.Items.Add ("(" Time2 ")" Hostname ":");

ListBoxRecv.Items.Add (strmsg);

sb.append (strmsg);

IF (sb.tostring (). Indexof ("/ x99 / x99)> - 1)

{

Break;

}

}

Statusbar1.Panels [1] .text = "Receive information is completed!"

//

// code decoding

Codeparse (sb.toString ());

//

Socket.shutdown (socketshutdown.both);

Socket.close ();

}

转载请注明原文地址:https://www.9cbs.com/read-49834.html

New Post(0)