WPF implementation socket Asynchronous communication example

Source: Internet
Author: User
Tags sendfile socket zip

Example One

The code is as follows Copy Code

public class Sockethelper
{
private IPAddress IP = null;
private int port = 0;
Private socket socket = NULL;
private static ManualResetEvent Connectdone = new ManualResetEvent (false);
private static ManualResetEvent Senddone = new ManualResetEvent (false);
private static ManualResetEvent Receivedone = new ManualResetEvent (false);
Public sockethelper (IPAddress IP, int port)
{
This.ip = IP;
This.port = port;
}
public void Startrun (string _filepath, String _filename, String _sourceid, String _userid, String _bookid, Long _timestamp , String _type)
{
Try
{
IPEndPoint remoteep = new IPEndPoint (IP, port);
Socket client = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
Client. BeginConnect (remoteEP, New AsyncCallback (Connectcallback), client);
Connectdone.waitone ();
if (client. Connected)
{
Client. SetSocketOption (Socketoptionlevel.socket, Socketoptionname.receivetimeout, 10000000);//5 seconds timeout
Long _contenlength = contentlength (_filepath + ". zip");
String head = "Content-length=" + _contenlength + "; filename=" + _filename + "; sourceid=" + _sourceid + "; userid=" + _user Id + "; bookid=" + _bookid + "; timestamp=" + _timestamp + "; type=" + _type + "; \ r \ n";
Send (client, head);
Senddone.waitone ();
Receive (client);
Receivedone.waitone ();
SendFile (0, client, _filepath + ". zip");
Receivedone.reset ();
Receive (client);
Receivedone.waitone ();
Client. Shutdown (Socketshutdown.both);
Client. Close ();
}
}
catch (Exception e)
{
Console.WriteLine (E.tostring ());
}
}
private void Connectcallback (IAsyncResult ar)
{
Try
{
Socket client = (socket) ar. asyncstate;
Client. EndConnect (AR);
Connectdone.set ();
}
catch (Exception e)
{
Console.WriteLine (E.tostring ());
}
}
private void Receive (Socket client)
{
Try
{
StateObject state = new StateObject ();
State.worksocket = client;
Client. BeginReceive (state.buffer, 0, stateobject.buffersize, 0, New AsyncCallback (ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine (E.tostring ());
}
}
private void ReceiveCallback (IAsyncResult ar)
{
Try
{
StateObject state = (stateobject) ar. asyncstate;
Socket client = State.worksocket;
int bytesread = client. EndReceive (AR);
if (Bytesread > 0)
{
String AA = Encoding.UTF8.GetString (state.buffer, 0, bytesread);
Receivedone.set ();
}
Else
{
All the data has arrived; Put it in response.
if (State.sb.Length > 1)
{
Response = state.sb.ToString ();
}
Signal that all bytes have been received.
Receivedone.set ();
}
}
catch (Exception ex)
{
throw new Exception (string. Format (' {0} server connection interrupted ', ex. message));
}
}
<summary>
File stream Send
</summary>
<param name= "_offset" ></param>
<param name= "_client" ></param>
<param name= "_path" ></param>
private void SendFile (Long _offset, Socket _client, String _path)
{
using (FileStream stream = new FileStream (_path, FileMode.Open))
{
File pointer points to 0-bit
Stream. Seek (_offset, seekorigin.begin);
NetworkStream NetStream = new NetworkStream (_client);
int length;
byte[] buf = new byte[1024];
while (length = stream. Read (buf, 0, buf. Length)) > 0)
{
Netstream.write (buf, 0, length);
Netstream.flush ();
}
}
}
<summary>
To get the size of a resource bundle
</summary>
<param name= "Path" ></param>
<returns></returns>
Private long ContentLength (string path)
{
Long _contenlength = 0;
using (FileStream stream = new FileStream (path, FileMode.Open))
{
_contenlength = stream. Length;
}
return _contenlength;
}
<summary>
Send the protocol header file
</summary>
<param name= "Client" ></param>
<param name= "Data" ></param>
private void Send (Socket client, String data)
{
byte[] Bytedata = Encoding.UTF8.GetBytes (data);
Client. BeginSend (bytedata, 0, bytedata.length, 0, New AsyncCallback (Sendcallback), client);
}
private void Sendcallback (IAsyncResult ar)
{
Try
{
Socket client = (socket) ar. asyncstate;
int bytessent = client. Endsend (AR);
Senddone.set ();
}
catch (Exception ex)
{
throw new Exception (string. Format (' {0} send callback failed ', ex. message));
}
}
}


Three ways to implement asynchronous sockets

The code is as follows Copy Code

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Net;
Using System.Net.Sockets;
Using Wintellect.Threading.AsyncProgModel;

Namespace Extensiontest
{
/*
* No exception handling before the two have not yet implemented continuous receive
* AsyncEnumerator from Jeffrey Rich's Wintellect
*/

public class Network
{
Private Const string IP = "localhost";
Private Const int port = 10101;

Private IPEndPoint EndPoint;
Private Socket server;

Public network ()
{
EndPoint = new IPEndPoint (Dns.gethostentry (IP). Addresslist[0], port);

Server = new Socket (AddressFamily.InterNetwork, SocketType.Stream, Protocoltype.ip);
Server. Bind (EndPoint);
Server. Listen (10);
}

public void startlistening ()
{
Server. BeginAccept (acceptcallback, server);
}

        public void Startlisteningwithiterator ()
         {
            AsyncEnumerator ASYCN = new AsyncEnumerator ();
            ASYCN. Execute (this. Startasync (ASYCN));
       }

private void Acceptcallback (IAsyncResult asyncresult)
{
Socket Server = asyncresult.asyncstate as Socket;
if (server!= null)
{
Socket receivesocket = server. Endaccept (asyncresult);

byte[] buffer = new BYTE[256];

Receivesocket.beginreceive (buffer, 0, buffer. Length, Socketflags.none, ReceiveCallback, New state (Receivesocket, buffer));

//
This. Startasync (Receivesocket);
}
}

private void ReceiveCallback (IAsyncResult asyncresult)
{
state state = asyncresult.asyncstate as State;

            if (state!= null)
             {
                 int recebytes = state. Socket.endreceive (asyncresult);
                if (Recebytes > 0)
                     state. Socket.beginsend (state. Bytes, 0, Recebytes, Socketflags.none, Sendcallback, state. Socket);
           }
       }

private void Sendcallback (IAsyncResult asyncresult)
{
Socket socket = asyncresult.asyncstate as socket;
if (socket!= null)
{
Socket. Endsend (asyncresult);
}
}

Private ienumerator<int> Startasync (AsyncEnumerator enumerator)
{
Server. BeginAccept (Enumerator. End (), null);

Yield return 1;

Socket receivesocket = server. Endaccept (Enumerator. Dequeueasyncresult ());

byte[] buffer = new BYTE[256];

Receivesocket.beginreceive (buffer, 0, buffer. Length, Socketflags.none, enumerator. End (), null);

Yield return 1;

int recelength = receivesocket.endreceive (enumerator. Dequeueasyncresult ());

if (Recelength > 0)
{
Receivesocket.beginsend (buffer, 0, Recelength, Socketflags.none, enumerator. End (), null);

Yield return 1;

Receivesocket.endsend (Enumerator. Dequeueasyncresult ());
}
Else
Yield break;
}

private void Startasync (socket socket)
{
AsyncCallback callback = null;

byte[] buffer = new BYTE[256];
callback = Receresult =>
{
int recelength = socket. EndReceive (Receresult);

if (Recelength > 0)
{
Socket. BeginSend (buffer, 0, recelength, Socketflags.none, Sendresult =>
{
Socket. Endsend (Sendresult);
Socket. BeginReceive (buffer, 0, buffer. Length, Socketflags.none, callback, NULL);
}, NULL);
}

};


Socket. BeginReceive (buffer, 0, buffer. Length, Socketflags.none, callback, NULL);
}

Private class State
{
Public socket sockets {get; private set;}
Public byte[] Bytes {get; private set;}

            public State (socket socket, byte[] bytes)
            {
                 this. socket = socket;
                this. Bytes = Bytes;
           }
       }
   }
}

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.