C # Socket transmission of large files

Source: Internet
Author: User

1. Basic TransferFiles, required by both client and server

using System;using System.Collections.Generic;using System.Text;using System.Net;using System.Net.Sockets;using System.Windows.Forms;namespace Server{    public class TransferFiles    {        public static int SendData(Socket s, byte[] data)        {            int total = 0;            int size = data.Length;            int dataleft = size;            int sent;            while (total < size)            {                sent = s.Send(data, total, dataleft, SocketFlags.None);                total += sent;                dataleft -= sent;            }            return total;        }        public static byte[] ReceiveData(Socket s, int size)        {            int total = 0;            int dataleft = size;            byte[] data = new byte[size];            int recv;            while (total < size)            {                recv = s.Receive(data, total, dataleft, SocketFlags.None);                if (recv == 0)                {                    data = null;                    break;                }                total += recv;                dataleft -= recv;            }            return data;        }        public static int SendVarData(Socket s, byte[] data)        {            int total = 0;            int size = data.Length;            int dataleft = size;            int sent;            byte[] datasize = new byte[4];            try            {                datasize = BitConverter.GetBytes(size);                sent = s.Send(datasize);                while (total < size)                {                    sent = s.Send(data, total, dataleft, SocketFlags.None);                    total += sent;                    dataleft -= sent;                }                return total;            }            catch            {                return 3;            }        }        public static byte[] ReceiveVarData(Socket s)        {            int total = 0;            int recv;            byte[] datasize = new byte[4];            recv = s.Receive(datasize, 0, 4, SocketFlags.None);            int size = BitConverter.ToInt32(datasize, 0);            int dataleft = size;            byte[] data = new byte[size];            while (total < size)            {                recv = s.Receive(data, total, dataleft, SocketFlags.None);                if (recv == 0)                {                    data = null;                    break;                }                total += recv;                dataleft -= recv;            }            return data;        }    }}

2. Server Side

Using System; using System. collections. generic; using System. text; using System. net; using System. net. sockets; using System. threading; using System. IO; using System. configuration; namespace Server {public static class FileServer {private static Socket serverSocket; public static void Init () {// Server ip address IPAddress ip = IPAddress. parse (ConfigurationManager. appSettings ["ListenIP"]); int myProt = Convert. toInt 32 (ConfigurationManager. appSettings ["ListenFilePort"]); serverSocket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); serverSocket. bind (new IPEndPoint (ip, myProt); // Bind an ip Address: Port serverSocket. listen (10); // you can set up to 10 queue connection requests to the Console. writeLine ("listener started {0} succeeded", serverSocket. localEndPoint. toString (); // send data through Clientsoket Thread myThread = new Thread (ListenClientConnect); myThread. S Tart ();} public static void Exit () {serverSocket. Close (); serverSocket = null;} private static void ListenClientConnect () {while (true) {if (serverSocket! = Null) {try {Socket clientSocket = serverSocket. accept (); Thread fig = new Thread (Create); fig. start (clientSocket) ;}catch {break ;}} public static void Create (object clientSocket) {Socket client = clientSocket as Socket; // obtain the client Node object IPEndPoint clientep = (IPEndPoint) client. remoteEndPoint; // obtain the [file name] string SendFileName = System. text. encoding. unicode. getString (Transfer Files. evardata (client); // check whether the local media library if (SocketServer. useLocal) {// close the Socket client. close (); return;} // obtain [package size] string bagSize = System. text. encoding. unicode. getString (TransferFiles. evardata (client); // obtain [total number of packages] int bagCount = int. parse (System. text. encoding. unicode. getString (TransferFiles. receiveVarData (client); // obtain the [size of the last package] string bagLast = System. text. encoding. unicode. getString (TransferFiles. incluevardata (client); string fullPath = Path. combine (Environment. currentDirectory, SendFileName); // create a new file FileStream MyFileStream = new FileStream (fullPath, FileMode. create, FileAccess. write); // Number of sent packets int SendedCount = 0; while (true) {byte [] data = TransferFiles. incluevardata (client); if (data. length = 0) {break;} else {SendedCount ++; // write the received data packet to the file stream object MyFileStream. wri Te (data, 0, data. length); // display the number of sent packets} // close the file stream MyFileStream. close (); // Close the Socket client. close (); SocketServer. pForm. showMessageBox (SendFileName + "received! ");}}}

3. Client

Using System; using System. collections. generic; using System. text; using System. IO; using System. net; using System. net. sockets; using System. diagnostics; namespace Client {public static class FileClient {public static bool SendFile (string IP, int Port, string fullPath) {// create a file object FileInfo EzoneFile = new FileInfo (fullPath ); // open the file stream FileStream EzoneStream = EzoneFile. openRead (); // The package size int PacketSize = 10 000; // Number of packages int PacketCount = (int) (EzoneStream. length/(long) PacketSize); // the size of the last package int LastDataPacket = (int) (EzoneStream. length-(long) (PacketSize * PacketCount); // point to the remote server node IPEndPoint ipep = new IPEndPoint (IPAddress. parse (IP), Port); // create Socket client = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); // connect to the sender try {client. connect (ipep);} catch {Debug. WriteLine ("failed to connect to the server! "); Return false;} // obtain the client Node object IPEndPoint clientep = (IPEndPoint) client. remoteEndPoint; // send [file name] to client TransferFiles. sendVarData (client, System. text. encoding. unicode. getBytes (EzoneFile. name); // send [package size] to client TransferFiles. sendVarData (client, System. text. encoding. unicode. getBytes (PacketSize. toString (); // send [total number of packages] to the client TransferFiles. sendVarData (client, System. text. encoding. unicode. getBytes (PacketCo Unt. toString (); // send [size of the last package] to the client TransferFiles. sendVarData (client, System. text. encoding. unicode. getBytes (LastDataPacket. toString (); bool isCut = false; // packet byte [] data = new byte [PacketSize]; // start to send packets cyclically (int I = 0; I <PacketCount; I ++) {// read data from the file stream and fill in the data packet EzoneStream. read (data, 0, data. length); // send the packet if (TransferFiles. sendVarData (client, data) = 3) {isCut = true; return false; bre Ak ;}} // if there are additional data packets, it should be sent! If (LastDataPacket! = 0) {data = new byte [LastDataPacket]; EzoneStream. read (data, 0, data. length); TransferFiles. sendVarData (client, data);} // close the Socket client. close (); // Close the file stream EzoneStream. close (); if (! IsCut) {return true ;}return false ;}}}

 

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.