Point-to-Point communication and file transfer using C # (Communication base class section)

Source: Internet
Author: User
Tags bool socket strlen port number
Recently a project to use point file transmission, I find information everywhere to write procedures, and finally completed, in order to let others take less detours, I decided to the most important part of the program to contribute out, I hope to help.



My program is divided into three parts, including the sending part, the acceptance part and a shared communication base class, this base class is my painstaking crystallization:



First, the communication base class

Using System;

Using System.Net.Sockets;

Using System.Net;

Using System.IO;

Using System.Windows.Forms;

Using System.Text;



Namespace BaseClass

{

<summary>

The format of the message is the command part of a given length + the command annotation section of a given length + variable length information + variable length information section

</summary>

public class Communclass

{

Public Communclass ()

{

//

TODO: Add constructor logic here

//

}

<summary>

Length of the command section

</summary>

private static readonly int cmdlen = 50;

<summary>

Length of the command annotation section

</summary>

private static readonly int desclen = 100;

<summary>

The length of the variable length information part of the number of bytes

</summary>

private static readonly int dynamiclengthlen = 10;

<summary>

Length of the Variable information section per process

</summary>

private static readonly int deallen = 1024;

<summary>

/answer Maximum length

</summary>

private static readonly int responlen = 20;

<summary>

Character used to populate a command or comment less than part of the length

</summary>

private static readonly char Fillchar = ' ^ ';



<summary>

A callback method (also considered a trigger event, but not strictly) after a successful sending of a portion of data

</summary>

public delegate void OnSend (int itotal,int isending);



<summary>

Establish a connection based on the given server and port number

</summary>

<param name= "Strhost" > Server name </param>

<param name= "Iport" > Port number </param>

<returns></returns>

public static Socket Connecttoserver (String strhost,int iport)

{

Try

{

IPAddress ipaddress = Dns.resolve (strhost). ADDRESSLIST[0];

IPEndPoint ippoint = new IPEndPoint (ipaddress,iport);



Socket s = new socket (ADDRESSFAMILY.INTERNETWORK,SOCKETTYPE.STREAM,PROTOCOLTYPE.TCP);

S.connect (Ippoint);

return s;

}

catch (Exception e)

{

Throw (New Exception ("Connection to the server error" + e.message));

}

}

<summary>

Write text to a socket

</summary>

<param name= "S" > socket</param> to send a message

<param name= "Strinfo" > Information to be sent </param>

<returns> Success </returns>

public static bool Writetexttosocket (Socket s,string strinfo)

{

byte [] buf = Encoding.UTF8.GetBytes (Strinfo);

Try

{

S.send (buf,0,buf. Length,socketflags.none);

return true;

}

catch (Exception err)

{

MessageBox.Show ("Send text failed!") "+err. message);

return false;

}

}

<summary>

Write command text to a socket

</summary>

<param name= "S" > The socket</param> to send the command text

<param name= "strinfo" > Command text to be sent </param>

<returns> Success </returns>

public static bool Writecommandtosocket (Socket s,string strcmd)

{

if (Strcmd = "")

Strcmd = "NOP";

Strcmd = Strcmd.padright (Cmdlen,fillchar);

Return Writetexttosocket (S,strcmd);

}

<summary>

Write a command comment to the socket

</summary>

<param name= "S" > to send a command comment socket</param>

<param name= "strinfo" > Command comments to be sent </param>

<returns> Success </returns>

public static bool Writecommanddesctosocket (Socket s,string Strdesc)

{

if (Strdesc = "")

Strdesc = "0";

Strdesc = Strdesc.padright (Desclen,fillchar);

Return Writetexttosocket (S,STRDESC);

}

<summary>

Number of bytes to send variable information

</summary>

<param name= "S" > The number of bytes to send socket</param>

<param name= "Ilen" > number of bytes </param>

<returns> Success </returns>

public static bool Writedynamiclentosocket (Socket s,int Ilen)

{

String strLen = Ilen.tostring (). PadRight (Dynamiclengthlen,fillchar);

Return Writetexttosocket (S,strlen);

}

<summary>

Sends the specified portion of the cache to the socket

</summary>

<param name= "S" > to send Cache socket</param>

<param name= "BUF" > Cache to send </param>

<param name= "IStart" > Where to send the cache start </param>

<param name= "Icount" > number of bytes to send cache </param>

<param name= "Iblock" > bytes per sent </param>

<param name= "sendsuccess" > callback function after each successful send </param>

<returns> whether to send success </returns>

public static bool Writebuftosocket (Socket s,byte [] buf,int istart,int icount,int iblock,onsend sendsuccess)

{

int isended = 0;

int isending = 0;

while (Isended<icount)

{

if (isended + iblock <= icount)

isending = Iblock;

Else

isending = icount-isended;

S.send (Buf,istart+isended,isending,socketflags.none);

isended + = isending;

if (Readresponsionfromsocket (s) = = "OK")

if (sendsuccess!= null)

Sendsuccess (icount,isended);

Else

return false;

}

return true;

}

<summary>

To send an unfixed length of text to a socket

</summary>

<param name= "S" > To send Text socket</param>

<param name= "StrText" > Text to be sent </param>

<param name= "Onsendtext" > callback function after successfully sending part of text </param>

<param name= "Settextlen" > get the text length of the callback function </param>

<returns></returns>

public static bool Writedynamictexttosocket (Socket s,string StrText,

OnSend Onsendtext)

{

byte [] buf = Encoding.UTF8.GetBytes (StrText);



int ilen = buf. Length;

Try

{

Writedynamiclentosocket (S,ilen);

Return Writebuftosocket (S,buf,0,ilen,deallen,onsendtext);

}

catch (Exception err)

{

MessageBox.Show ("Send text failed!") "+err. message);

return false;

}

}

<summary>

Write a file to a socket

</summary>

<param name= "S" > to send a file socket</param>

<param name= "strfile" > Files to send </param>

<returns> Success </returns>

public static bool Writefiletosocket (Socket s,string strfile,

OnSend onsendfile)

{

FileStream fs = new FileStream (strfile,filemode.open,fileaccess.read,fileshare.read);

int ilen = (int) fs. Length;

Writedynamiclentosocket (S,ilen);

byte [] buf = new Byte[ilen];

Try

{

Fs. Read (Buf,0,ilen);

Return Writebuftosocket (S,buf,0,ilen,deallen,onsendfile);

}

catch (Exception err)

{

MessageBox.Show ("Send file failed!") "+err. message);

return false;

}

Finally

{

Fs. Close ();

}

}

<summary>

The other person's simple response to their message

</summary>

<param name= "S" ></param>

<returns></returns>

public static string Readresponsionfromsocket (Socket s)

{

byte [] bufcmd = new Byte[responlen];

int icount = s.receive (bufcmd);

String strrespon = Encoding.UTF8.GetString (Bufcmd,0,icount);

return strrespon;

}

<summary>

Reading commands from the socket

</summary>

<param name= "S" > the socket</param> to read the command

<returns> Read the commands </returns>

public static string Readcommandfromsocket (Socket s)

{

byte [] bufcmd = new Byte[cmdlen];

int icount = s.receive (bufcmd,0,cmdlen,socketflags.partial);

String strcommand = Encoding.UTF8.GetString (Bufcmd,0,cmdlen);

return strcommand = Strcommand.trimend (Fillchar);

}

<summary>

Read command comment

</summary>

<param name= "S" > to read the command comment socket</param>

<returns> Read command notes </returns>

public static string Readcommanddescfromsocket (Socket s)

{

byte [] bufcmd = new Byte[desclen];

int icount = s.receive (bufcmd,0,desclen,socketflags.partial);

String strcommand = Encoding.UTF8.GetString (Bufcmd,0,desclen);

return strcommand = Strcommand.trimend (Fillchar);

}

<summary>

Read the length of the variable part

</summary>

<param name= "S" > to read socket</param> of variable part length

<returns> read the length of the variable part </returns>

public static int Readdynamiclenfromsocket (Socket s)

{

byte [] bufcmd = new Byte[dynamiclengthlen];

int icount = s.receive (bufcmd,0,dynamiclengthlen,socketflags.partial);

String strcommand = Encoding.UTF8.GetString (Bufcmd,0,dynamiclengthlen);

return int. Parse (Strcommand.trimend (Fillchar));

}

<summary>

Read variable information in text form

</summary>

<param name= "S" > to read variable information socket</param>

<returns> Read variable information </returns>

public static string Readdynamictextfromsocket (Socket s)

{

int Ilen = Readdynamiclenfromsocket (s);



byte [] buf = new Byte[ilen];

String strinfo = "";



int ireceiveded = 0;

int ireceiveing = 0;

while (Ireceiveded<ilen)

{

if (ireceiveded + deallen <= ilen)

ireceiveing = Deallen;

Else

ireceiveing = ilen-ireceiveded;

S.receive (Buf,ireceiveded,ireceiveing,socketflags.none);

Communclass.writetexttosocket (S, "OK");

ireceiveded+= ireceiveing;

}



Strinfo = Encoding.UTF8.GetString (Buf,0,ilen);



return strinfo;

}

<summary>

Read variable information in file form

</summary>

<param name= "S" > to read variable information socket</param>

<param name= "strfile" > read out File save location </param>

<returns> Read Success </returns>

public static bool Readdynamicfilefromsocket (Socket s,string strfile)

{

int Ilen = Readdynamiclenfromsocket (s);

byte [] buf = new Byte[ilen];

FileStream fs = new FileStream (strfile,filemode.create,fileaccess.write);



Try

{

int ireceiveded = 0;

int ireceiveing = 0;

while (Ireceiveded<ilen)

{

if (ireceiveded + deallen <= ilen)

ireceiveing = Deallen;

Else

ireceiveing = ilen-ireceiveded;

S.receive (Buf,ireceiveded,ireceiveing,socketflags.none);

Communclass.writetexttosocket (S, "OK");

ireceiveded+= ireceiveing;

}

Fs. Write (Buf,0,ilen);

return true;

}

catch (Exception err)

{

MessageBox.Show ("Receive file Failed" +err. message);

return false;

}

Finally

{

Fs. Close ();

}

}

}//end class

}//end namespace

Above is my communication base class, with this class, and then send the acceptance is not a piece of cake?

To be Continued




Related Article

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.