C # File Transfer

Source: Internet
Author: User
Tags bind continue ftp get ip connect socket thread ftp protocol

The System.sockes namespace implements the Berkeley socket interface. Through this class, we can implement the message transmission and send between the network computer. And in the subject that I'm going to discuss below, we're going to talk about implementing file transfers with a set of nodes. This method is different from the FTP protocol, which requires a dedicated server and client to use the FTP method. There is no doubt that the point-to-point file transfer we are trying to implement is too complex. Here, we implement a lightweight approach to point-to-point file transfer, which achieves file sharing for any two computers on the intenet.

Before two computers transfer files, it is necessary to have a computer set up a nested node and bind a fixed port, and on this port listen for a connection request from another computer.

Socket = new Socket (addressfamily.internetwork,sockettype.stream, protocoltype.tcp);
Socket. Blocking = true;
IPEndPoint computernode1 = new IPEndPoint (serveripadress, 8080);

Socket. Bind (COMPUTERNODE1);

Socket. Listen (-1);

When a connection request is made by another computer, the requested computer assigns a thread to each connection request for processing file transfers and other services.

while (true)

{

Clientsock = socket. Accept ();

if (Clientsock. Connected)

{

Thread TC = new Thread (new ThreadStart (listenclient));

Tc. Start ();

}

}

The following code shows how the Listenclient method handles requests sent over from another computer. First, make a judgment on the request string sent over, see what kind of request it is, and then decide on the appropriate processing method.

void Listenclient ()
{
Socket sock = Clientsock;
Try
{
while (sock!= null)
{
byte[] RECs = new byte[32767];
int rcount = sock. Receive (recs,recs. length,0);
String message = System.Text.Encoding.ASCII.GetString (RECs);
Processing of message, parsing request characters and parameters stored in cmdlist
EXECMD=CMDLIST[0];
sender = null;
Sender = new byte[32767];

String parm1 = "";
Directory Enumeration
if (Execmd = = "LISTING")
{
Listfiles (message);
Continue;
}
File transfer
if (Execmd = = "Getok")
{
cmd = "BeginSend" + filepath + "" + filesize;
Sender = new byte[1024];
Sender = Encoding.ASCII.GetBytes (cmd);
Sock. Send (sender, sender. Length, 0);
Go to file download process
Downloadingfile (sock);
Continue;
}
}
}
catch (Exception Se)
{
string s = se.message;
Console.WriteLine (s);
}
}

Now that the basic work has been done, let's look at how to handle the file transfer.
while (Rdby < Total && NFS. CanWrite)
{
Reads the specified length of data from the file to be transferred
Len =fin. Read (buffed,0,buffed. Length);
Send the read data to the corresponding computer
Nfs. Write (buffed, 0,len);
Increase the length that has been sent
Rdby=rdby+len;
}
From the above code can be seen is the completion of the file into a FileStream stream, and then through the NetworkStream binding the corresponding set of nodes, and finally call his write method sent to the corresponding computer.
Let's look at how the receiving end accepts the transmitted stream and converts it to a file:
NetworkStream NFS = new NetworkStream (sock);
Try
{
Loop until the specified file length
while (Rby < size)
{
byte[] buffer = new byte[1024];
Read the stream of files sent over
int i = NFS. Read (Buffer,0,buffer. Length);
Fout. Write (buffer,0, (int) i);
Rby=rby+i;
}
Fout. Close ();

It can be seen from above that accepting and sending is exactly the opposite process, very simple.

Get a pre-saved file name
String Filename= "Test.rar";
Remote host
String Hostname=textboxhost.text.trim ();
Port
int port=80;
Get host information
Iphostentry Ipinfo=dns.gethostbyname (hostName);
Get ipaddress[]
Ipaddress[] ipaddr=ipinfo.addresslist;
Get IP
IPAddress Ip=ipaddr[0];
Combining a remote endpoint
IPEndPoint hostep=new IPEndPoint (ip,port);
Create a Socket instance
Socket socket=new socket (ADDRESSFAMILY.INTERNETWORK,SOCKETTYPE.STREAM,PROTOCOLTYPE.TCP);
Try
{
Trying to connect
Socket. Connect (Hostep);
}
catch (Exception se)
{
LeixunCMS.Common.MessageBox.Show (this. Page, "Connection error" +se. message);

}



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.