C# 超大文件发送与接收
发送端部分代码:
public void startSendFileThread() {
try
{
Thread sendFileThread = new Thread(new ThreadStart(sendFile));
sendFileThread.Start();
}
catch {
MessageBox.Show("线程开启或线程发送过中遇到问题失败。。。。。。");
this.sendFlag = false;
}
finally
{
}
}
public void sendFile()
{
public Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(userIP),userPort);
try
{
//因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
socketClient.SendBufferSize = 1024 * 1024*10;
socketClient.ReceiveBufferSize = 1024 * 1024*10;
socketClient.Connect(ipep);
// MessageBox.Show("connected!!");
}
catch (SocketException e)
{
Console.WriteLine("unable to connect to server");
Console.WriteLine(e.ToString());
}
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
int partSize = 1024 * 100;
long fileLength = fs.Length;
long offset = 0;
while (true)
{
if (offset + partSize >=fileLength)
partSize = Convert.ToInt32(fileLength - offset);
byte[] temp = new byte[partSize];
fs.Position = offset;
fs.Read(temp, 0, partSize);
socketClient.Send(temp, temp.Length, SocketFlags.None);//将数据发送到指定的终结点
// myControl.TraFransfersSize += partSize;
if (offset + partSize >= fileLength)
break;
offset += partSize;
}
//myChat.Rich_Out.AppendText("发送完成: " + fileName + "\n");
socketClient.Shutdown( SocketShutdown.Both);
socketClient.Close();
// myChat.RemoveFileInfoFromControl(fileName);
}
接收端部分代码:
public void Listener() //监听 本地端口5421
{
if (classTCPSocket == null)
classTCPSocket = new ClassTCPSocket(5421);
else
{
try
{
thdUdp = new Thread(new ThreadStart(GetUDPData)); //创建一个线程
thdUdp.Start(); //执行当前线程
}
catch (Exception e)
&nbs
补充:软件开发 , C# ,