C# Socket 文件传输 – 潜行怪的专栏 – 博客频道 – CSDN.NET

socketc#bytethreadstringbutton

 

 

 

 

如果需要接收多个文件的时候,不能重复调用Socket.Bind(ipep),这样会出现socket异常的,因为socket已经监听了一个端口了,端口不能被重复使用。

 

 

完整代码:

 

发送端。。client

[csharp] view plaincopyprint?

  1.      private void button2_Click(object sender, EventArgs e)
  2.      {
  3.          this.button2.Enabled = false;
  4.          Thread TempThread = new Thread(new ThreadStart(this.StartSend));
  5.          TempThread.Start();
  6.      }
  7.      private void StartSend()
  8.      {
  9.          //FileInfo EzoneFile = new FileInfo(this.textBox1.Text);
  10.          string path = @“E:\old F directory\TangWei\kangge\new1.jpg”;
  11.          FileInfo EzoneFile = new FileInfo(path);
  12.          FileStream EzoneStream = EzoneFile.OpenRead();
  13.          int PacketSize = 100000;
  14.          int PacketCount = (int)(EzoneStream.Length / ((long)PacketSize));
  15.      //    this.textBox8.Text = PacketCount.ToString();
  16.      //    this.progressBar1.Maximum = PacketCount;
  17.          int LastDataPacket = (int)(EzoneStream.Length – ((long)(PacketSize * PacketCount)));
  18.      //    this.textBox9.Text = LastDataPacket.ToString();
  19.          IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(“163.180.117.229”), 7000);
  20.          Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  21.          client.Connect(ipep);
  22. //         TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(EzoneFile.Name));
  23. //         TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketSize.ToString()));
  24.  //        TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketCount.ToString()));
  25.  //        TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(LastDataPacket.ToString()));
  26.          byte[] data = new byte[PacketSize];
  27.          for(int i=0; i<PacketCount; i++)
  28.          {
  29.              EzoneStream.Read(data, 0, data.Length);
  30.              TransferFiles.SendVarData(client, data);
  31. //             this.textBox10.Text = ((int)(i + 1)).ToString();
  32. //             this.progressBar1.PerformStep();
  33.          }
  34.          if(LastDataPacket != 0)
  35.          {
  36.              data = new byte[LastDataPacket];
  37.              EzoneStream.Read(data, 0, data.Length);
  38.              TransferFiles.SendVarData(client,data);
  39.  //            this.progressBar1.Value = this.progressBar1.Maximum;
  40.          }
  41.          client.Close();
  42.          EzoneStream.Close();
  43.          this.button2.Enabled = true;
  44.      }

{

this.button2.Enabled = false;

Thread TempThread = new Thread(new ThreadStart(this.StartSend));

TempThread.Start();

}

private void StartSend()

{

//FileInfo EzoneFile = new FileInfo(this.textBox1.Text);

string path = @”E:\old F directory\TangWei\kangge\new1.jpg”;

FileInfo EzoneFile = new FileInfo(path);

FileStream EzoneStream = EzoneFile.OpenRead();

int PacketSize = 100000;

int PacketCount = (int)(EzoneStream.Length / ((long)PacketSize));

// this.textBox8.Text = PacketCount.ToString();

// this.progressBar1.Maximum = PacketCount;

int LastDataPacket = (int)(EzoneStream.Length – ((long)(PacketSize * PacketCount)));

// this.textBox9.Text = LastDataPacket.ToString();

IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(“163.180.117.229”), 7000);

Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

client.Connect(ipep);

// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(EzoneFile.Name));

// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketSize.ToString()));

// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketCount.ToString()));

// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(LastDataPacket.ToString()));

byte[] data = new byte[PacketSize];

for(int i=0; i<PacketCount; i++)

{

EzoneStream.Read(data, 0, data.Length);

TransferFiles.SendVarData(client, data);

// this.textBox10.Text = ((int)(i + 1)).ToString();

// this.progressBar1.PerformStep();

}

if(LastDataPacket != 0)

{

data = new byte[LastDataPacket];

EzoneStream.Read(data, 0, data.Length);

TransferFiles.SendVarData(client,data);

// this.progressBar1.Value = this.progressBar1.Maximum;

}

client.Close();

EzoneStream.Close();

this.button2.Enabled = true;

}

 

接收端   server

[csharp] view plaincopyprint?

  1.    private void button2_Click(object sender, EventArgs e)
  2.     {
  3.         //int i = 0;
  4.         //FileStream recfs = new FileStream(“E:\\kangge.jpg”, FileMode.OpenOrCreate);
  5.         //Byte[] recbyte = new Byte[2000000];
  6.         //Socket hostsocket = receive.Accept();
  7.         //BinaryWriter newfilestr = new BinaryWriter(recfs);
  8.         //hostsocket.Receive(recbyte, recbyte.Length, SocketFlags.None);
  9.         //for (i = 0; i < recbyte.Length; i++)
  10.         //{
  11.         //    newfilestr.Write(recbyte, i, 1);
  12.         //}
  13.         //recfs.Close();
  14.         //hostsocket.Shutdown(SocketShutdown.Receive);
  15.         //hostsocket.Close();
  16.         this.button2.Enabled = false;
  17.         Thread TempThread = new Thread(new ThreadStart(this.StartReceive));
  18.         TempThread.Start();
  19.     }
  20.     private void StartReceive()
  21.     {
  22.         IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(“163.180.117.229”), 7000);
  23.         Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  24.         server.Bind(ipep);
  25.         server.Listen(10);
  26.         Socket client = server.Accept();
  27.  //       IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
  28.   //      string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
  29.    //     string BagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
  30.   //      int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)));
  31.   //      string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
  32.         int file_name = 1;
  33.         string fileaddr = “E:\\old F directory\\TangWei\\Copy of kangge\\” + file_name.ToString() + “.jpg”;
  34.         FileStream MyFileStream = new FileStream(fileaddr, FileMode.Create, FileAccess.Write);
  35. //        int SendedCount = 0;
  36.         while(true)
  37.         {
  38.             byte[] data = TransferFiles.ReceiveVarData(client);
  39.             if(data.Length == 0)
  40.             {
  41.                 break;
  42.             }
  43.             else
  44.             {
  45.                // SendedCount++;
  46.                 MyFileStream.Write(data, 0, data.Length);
  47.             }
  48.         }
  49.         MyFileStream.Close();
  50.         client.Close();
  51.         this.button2.Enabled = true;
  52.     }

{

//int i = 0;

//FileStream recfs = new FileStream(“E:\\kangge.jpg”, FileMode.OpenOrCreate);

//Byte[] recbyte = new Byte[2000000];

//Socket hostsocket = receive.Accept();

//BinaryWriter newfilestr = new BinaryWriter(recfs);

//hostsocket.Receive(recbyte, recbyte.Length, SocketFlags.None);

//for (i = 0; i < recbyte.Length; i++)

//{

// newfilestr.Write(recbyte, i, 1);

//}

//recfs.Close();

//hostsocket.Shutdown(SocketShutdown.Receive);

//hostsocket.Close();

this.button2.Enabled = false;

Thread TempThread = new Thread(new ThreadStart(this.StartReceive));

TempThread.Start();

}

private void StartReceive()

{

IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(“163.180.117.229”), 7000);

Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

server.Bind(ipep);

server.Listen(10);

Socket client = server.Accept();

// IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;

// string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));

// string BagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));

// int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)));

// string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));

int file_name = 1;

string fileaddr = “E:\\old F directory\\TangWei\\Copy of kangge\\” + file_name.ToString() + “.jpg”;

FileStream MyFileStream = new FileStream(fileaddr, FileMode.Create, FileAccess.Write);

// int SendedCount = 0;

while(true)

{

byte[] data = TransferFiles.ReceiveVarData(client);

if(data.Length == 0)

{

break;

}

else

{

// SendedCount++;

MyFileStream.Write(data, 0, data.Length);

}

}

MyFileStream.Close();

client.Close();

this.button2.Enabled = true;

}

 

公共类。 TransferFiles

[csharp] view plaincopyprint?

  1. class TransferFiles
  2. {
  3.     public TransferFiles()
  4.     {
  5.     }
  6.     public static int SendVarData(Socket s, byte[] data) // return integer indicate how many data sent.
  7.     {
  8.         int total = 0;
  9.         int size = data.Length;
  10.         int dataleft = size;
  11.         int sent;
  12.         byte[] datasize = new byte[4];
  13.         datasize = BitConverter.GetBytes(size);
  14.         sent = s.Send(datasize);//send the size of data array.
  15.         while (total < size)
  16.         {
  17.             sent = s.Send(data, total, dataleft, SocketFlags.None);
  18.             total += sent;
  19.             dataleft -= sent;
  20.         }
  21.         return total;
  22.     }
  23.     public static byte[] ReceiveVarData(Socket s) // return array that store the received data.
  24.     {
  25.         int total = 0;
  26.         int recv;
  27.         byte[] datasize = new byte[4];
  28.         recv = s.Receive(datasize, 0, 4, SocketFlags.None);//receive the size of data array for initialize a array.
  29.         int size = BitConverter.ToInt32(datasize, 0);
  30.         int dataleft = size;
  31.         byte[] data = new byte[size];
  32.         while (total < size)
  33.         {
  34.             recv = s.Receive(data, total, dataleft, SocketFlags.None);
  35.             if (recv == 0)
  36.             {
  37.                 data = null;
  38.                 break;
  39.             }
  40.             total += recv;
  41.             dataleft -= recv;
  42.         }
  43.         return data;
  44.     }
  45. }

{

public TransferFiles()

{

}

public static int SendVarData(Socket s, byte[] data) // return integer indicate how many data sent.

{

int total = 0;

int size = data.Length;

int dataleft = size;

int sent;

byte[] datasize = new byte[4];

datasize = BitConverter.GetBytes(size);

sent = s.Send(datasize);//send the size of data array.

while (total < size)

{

sent = s.Send(data, total, dataleft, SocketFlags.None);

total += sent;

dataleft -= sent;

}

return total;

}

public static byte[] ReceiveVarData(Socket s) // return array that store the received data.

{

int total = 0;

int recv;

byte[] datasize = new byte[4];

recv = s.Receive(datasize, 0, 4, SocketFlags.None);//receive the size of data array for initialize a array.

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;

}

}

来源URL:http://blog.csdn.net/tw7613781/article/details/6736911