zoukankan      html  css  js  c++  java
  • socket+TCP文件传输

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;

    namespace SocketFileSend
    {
    public partial class Form1 : Form
    {
    Socket Listensocket;
    public Form1()
    {
    InitializeComponent();
    }

    //选取要发送的文件
    private void BtnSelectFile_Click(object sender, EventArgs e)
    {
    if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
    {
    FileInfo fileinfo = new FileInfo(this.openFileDialog1.FileName);
    TBFileName.Text = fileinfo.FullName;
    TBFileSize.Text = fileinfo.Length.ToString();
    }
    }
    //开始监听
    private void btnListen_Click(object sender, EventArgs e)
    {
    //服务端节点
    IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.1.102"), 8000);
    //创建套接字
    Listensocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    //绑定IP地址和端口到套接字
    Listensocket.Bind(ipep);
    //启动监听
    Listensocket.Listen(10);
    listBox1.Items.Add("开始监听客户端的连接请求");
    //在一个单独的线程中监听客户连接
    Thread listenThread = new Thread(listenClientConnnect);
    listenThread.Start();
    }

    private void listenClientConnnect()
    {
    while (true)
    {
    //建立一个与客户端通信的套接字
    Socket CommunicationSocket = Listensocket.Accept();
    //创建一个文件对象
    FileInfo fileinfo = new FileInfo(TBFileName.Text);
    //打开文件流
    FileStream filestream = fileinfo.OpenRead();
    //文件分块传输,分块的大小,单位为字节
    int PacketSize = 5000;
    //分块的数量
    int PacketCount = (int)(fileinfo.Length / ((long)PacketSize));
    //最后一个分块的大小
    int LastPacketSize = (int)(fileinfo.Length - ((long)(PacketSize * PacketCount)));
    //发送文件名到接收端,文件名长度最多只允许100个字节
    byte[] Fullfilename = new byte[100];
    if (System.Text.Encoding.UTF8.GetBytes(fileinfo.Name).Length > 100)
    {
    MessageBox.Show("文件名太长");
    break;
    }
    else
    {
    byte[] filename=System.Text.Encoding.UTF8.GetBytes(fileinfo.Name);
    for (int i = 0; i < filename.Length; i++)
    Fullfilename[i] = filename[i];
    CommunicationSocket.Send(Fullfilename);
    }

    //文件按数据包的形式发送,定义数据包的大小
    byte[] data=new byte[PacketSize];
    //开始循环发送数据包
    for(int i=0;i<PacketCount;i++)
    {
    //从文件流读取数据并填充数据包
    filestream.Read(data, 0, data.Length);
    //发送数据包
    CommunicationSocket.Send(data, 0, data.Length, SocketFlags.None);
    }

    //发送最后一个数据包
    if (LastPacketSize != 0)
    {
    data = new byte[LastPacketSize];
    filestream.Read(data, 0, data.Length);
    //发送数据包
    CommunicationSocket.Send(data, 0, data.Length, SocketFlags.None);
    }
    filestream.Close();
    CommunicationSocket.Close();
    MessageBox.Show("发送完毕");
    }
    }


    //关闭窗体时发生
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
    Listensocket.Close();
    }


    }
    }

    以上是发送端代码。下面是接收端代码

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    using System.Threading;

    namespace SocketFileReceive
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    private void btnConnect_Click(object sender, EventArgs e)
    {
    Thread mythread = new Thread(GetData);
    mythread.Start();
    }

    private void GetData()
    {
    //创建网络端点
    IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.1.102"), 8000);
    //创建套接字
    Socket clientsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    //连接远程服务器
    try
    {
    clientsocket.Connect(ipep);
    listBox1.Items.Add("连接远程服务器成功");
    }
    catch
    {
    listBox1.Items.Add("连接远程服务器失败");
    }
    //接收文件的名称
    string filename = System.Text.Encoding.UTF8.GetString(ReceiveStrToByte(clientsocket)).Split('\0')[0];
    //创建一个新文件

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


    int PacketSize = 5000;
    //定义一个完整数据包缓存
    byte[] data = new byte[PacketSize];
    while (true)
    {
    int revcount = clientsocket.Receive(data, 0, PacketSize, SocketFlags.None);
    if (revcount == 0)
    {
    data = null;
    break;
    }
    //处理最后一个数据包
    if (revcount != PacketSize)
    {
    byte[] lastdata = new byte[revcount];
    for (int i = 0; i < revcount; i++)
    lastdata[i] = data[i];
    //将接收到的最后一个数据包写入到文件流对象
    MyFileStream.Write(lastdata, 0, lastdata.Length);
    lastdata = null;
    }
    else
    {
    //将接收到的数据包写入到文件流对象
    MyFileStream.Write(data, 0, data.Length);
    }
    }
    //关闭文件流
    MyFileStream.Close();
    //关闭套接字
    clientsocket.Close();
    MessageBox.Show("接收完毕");
    }

    //关闭窗体时发生
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {

    }

    //接收函数,(文件名最多100个字节)
    private byte[] ReceiveStrToByte(Socket s)
    {
    try
    {
    byte[] dataninfo = new byte[100];
    int revByteNum = s.Receive(dataninfo, 0, dataninfo.Length, SocketFlags.None);
    byte[] retByte = new byte[revByteNum];
    for (int i = 0; i < revByteNum; i++)
    retByte[i] = dataninfo[i];
    return retByte;
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    return null;
    }
    }
    }
    }
  • 相关阅读:
    英语语法基础知识总结名词
    英语语法基础知识代词
    idea破解第二部
    Linux(centos)系统下安装fastdfs安装部署步骤
    死磕Synchronized底层实现概论偏向锁轻量级锁重量级锁
    深入理解Mysql事务隔离级别与锁机制
    事务的传播机制
    ICCV2021 | TokenstoToken ViT:在ImageNet上从零训练Vision Transformer
    计算机视觉CV技术指南文章汇总
    资源分享 | PyTea:不用运行代码,静态分析pytorch模型的错误
  • 原文地址:https://www.cnblogs.com/guoyuanwei/p/2359588.html
Copyright © 2011-2022 走看看