Use C # to do point-to-point communication and file transfer (communication base class)

zhaozj2021-02-16  158

[

Original link], the author:

Tashanzhishi

Recently, a project should use some point to transfer, and you will find the information written by the data. Finally, finally completed, in order to let others walk less, I decided to contribute the most important part of the program, I hope to help everyone. .

The procedures are divided into three parts, including the sending part, accept the part and a communication base class shared, this base class is the crystallization of the heart :)

I. Communication base class

Using system;

Using system.net.sockets;

Using system.net;

Using system.io;

Using system.windows.forms;

Using system.text;

Namespace Baseclass

{

///

/// The format of transmitting information is the command portion of the given length a given length of the command notes part variable length length information variable length information section

///

Public Class Communclass

{

Public CommunClass ()

{

//

// TODO: Add constructor logic here

//

}

///

/// Command part of the length

///

Private static readonly int cmdlen = 50;

///

/ / / Command the length of the part

///

Private static readonly int desclen = 100;

///

The number of bytes occupying the length of the variable length

///

Private static readonly int Dynamicles;

///

// / The length of the variable information portion is processed each time

///

Private static readonly int devaten = 1024;

///

/// / answer maximum length

///

Private static readonly int responlen = 20;

///

/// The character used to fill the command or notes the length of the length of the length.

///

Private static readonly char fillchar = '^';

///

// / Successfully send a part of the callback method (or if it is also a triggered event, but strictly said yet)

///

Public Delegate Void Onsend (int itotal, int tenting);

///

// Establish a connection according to a given server and port number

///

/// server name

/// port number

///

Public Static Socket ConnectTOServer (String strHost, int port)

{

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 " E.Message)); E.MESSAGE));

}

}

///

/// Write text into the socket

///

/// Socket to send information

/// Information to send

/// Whether it is successful

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;

}

}

///

/// Write the command text into the socket

///

/// Socket to send command text

/// command text to send

/// Whether it is successful

Public Static Bool WriteCommandtosocket (Socket S, String Strcmd)

{

IF (strcmd == "")

STRCMD = "NOP";

Strcmd = strcmd.padright (cmdlen, fillchar);

Return WriteTextTosocket (S, STRCMD);

}

///

/// Write command notes into socket

///

/// Socket to send a command comment

/// The command notes you want to send

/// Whether it is successful

Public Static Bool WriteCommandDesctOSocket (Socket S, String Strdesc)

{

IF (strDesc == "")

STRDESC = "0";

STRDESC = STRDESC.PADRIGHT (DESCLEN, FILLCHAR); RETURN WRITETEXTOSOCKET (S, STRDESC);

}

///

/// Send the number of bytes of variable information

///

/// Socket to send bytes

/// bytes Number

/// Whether it is successful

Public Static Bool WriteDynamiclentosocket (Socket S, INT Ilen)

{

String strlen = Ilen.toT7tring (). Padright (Dynamicles); Fillchar

Return WriteTextTosocket (S, Strlen);

}

///

/// Send the cached specified section to socket

///

/// Socket to send cached

/// The cache to send

/// To send cache start position

/// Number of bytes to send cache

/// The byte of each sending

/// The callback function after successful call is sent

/// Whether to send success

Public Static Bool Writebuftosocket (Socket S, Byte [] BUF, Istart, Int Icount, Int Iblock, Onsend SendSuccess

{

INT ISENDED = 0;

INT ISENDING = 0;

While (Isended

{

IF (isended iblock <= iCount)

isending = iblock;

Else

isending = iCount - isended;

S.send (buf, iStart isended, isending, socketflags.none);

isended = isending;

IF (readResponsefromsocket (s) == "ok")

IF (SendSuccess! = null)

Sendsuccess (iCount, Isended);

Else

Return False;

}

Return True;

}

///

/// Send the length of not fixed text to Socket

///

/// Socket to send text

/// Text to send /// Successfully send a part of the callback function after text

/// Get the callback function of the text length

///

Public Static Bool WriteDynamicTextTosocket (Socket S, String Strtext,

Onsend onsendtext)

{

BYTE [] buf = encoding.utf8.getbytes (strText);

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;

}

}

///

/// Write the file to the socket

///

/// Socket to send files

/// File to send

/// Whether it is successful

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.lend

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 ();

}

}

///

/// The other party's simple response to yourself

///

///

///

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 Strress

}

///

/// Read commands from Socket

///

/// Socket to read the command

/// Read command

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);

}

///

/// read command notes

///

/// Socket to read the command annotation

/// Read the command notes

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);

}

///

/// Read the length of the variable portion

///

/// Socket to read variable part length

/// The length of the variable portion read

Public Static Int ReadDynamiclenfromsocket (Socket S)

{

BYTE [] bufcmd = new byte [Dynamicles];

Int iCount = S.Receive (bufcmd, 0, dynamiclengthlen, socketflags.partial);

String strcommand = encoding.utf8.getstring (bufcmd, 0, dynamiclengthlen);

Return Int.Parse (STRCOMMAND.TRIMEND (Fillchar));

}

///

/// Read variable information in text form

///

/// Socket to read variable information

/// Reading variable information

Public Static String ReadDynamicTextFromsocket (Socket S)

{

INT Ilen = ReadDynamicles; FromSocket (s);

Byte [] buf = new byte [Ilen]; String strinfo = "";

INT IRECEIVEDED = 0;

IRECEIVEING = 0;

While (IreceiveDed

{

IReceiveded DEALLEN <= Ilen)

Ireceiveing ​​= DEALLEN

Else

IRECEIVEING = Ilen - IreceiveDed;

S.Receive (buf, Ireceived, Ireceiveing, SocketFlags.none);

Communclass.writetexttosocket (S, "OK");

IreceiveDed = IRECEIVEING;

}

Strinfo = encoding.utf8.getstring (buf, 0, ilen);

Return Strinfo;

}

///

/// read variable information in the form of file

///

/// Socket to read variable information

/// After reading the file save location

/// Do you read successfully

Public Static Bool ReadDynamicFileFromSocket (socket s, string strfile)

{

INT Ilen = ReadDynamicles; FromSocket (s);

BYTE [] BUF = New byte [Ilen];

FILESTREAM FS = New FileStream (Strfile, FileMode.create, FileAccess.write);

Try

{

INT IRECEIVEDED = 0;

IRECEIVEING = 0;

While (IreceiveDed

{

IReceiveded DEALLEN <= Ilen)

Ireceiveing ​​= DEALLEN

Else

IRECEIVEING = Ilen - IreceiveDed;

S.Receive (buf, Ireceived, 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

The above is the newsletter class, with this class, and then send acceptance is not a plate for a dish?

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

New Post(0)