cidy3 2017-03-07 03:31 采纳率: 0%
浏览 934

C# 自攻自受型文件传输程序

刚开始学习网络编程,做了一个局域网内的文件传输程序,分开客户端和服务器端的时候,文件接收和传送都没问题,合并到一起之后,接收到的字符数组总是为0,请大家指点指点。

  • 写回答

1条回答 默认 最新

  • cidy3 2017-03-07 03:32
    关注
     using System;
    using System.Text;
    using System.IO;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    
    namespace FileTransmit
    {
        public partial class FileTransmit : Form
        {
            delegate void changeControlState();
            private void setControlState()
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new changeControlState(setControlState));
                    return;
                }
                btn_Transmit.Enabled = true;
            }
    
            public FileTransmit()
            {
                InitializeComponent();
                tex_IP1.Text = "192";
                tex_IP2.Text = "168";
                tex_IP3.Text = "1";
                tex_IP4.Text = "109";
    
                IPEndPoint hostEP_Server = new IPEndPoint(IPAddress.Any, 0368);
                fileTranser_Server.socket_Server.Bind(hostEP_Server);
                fileTranser_Server.socket_Server.Listen(5);
                //开启 线程接收数据
                fileTranser_Server.tReceive = new Thread(fileTranser_Server.fileReceive);
                fileTranser_Server.tReceive.IsBackground = true;
                fileTranser_Server.tReceive.Start();
            }
    
            //组合 数据包
            private byte[] CombomBinaryArray(byte[] srcArray1, byte[] srcArray2)
            {
                byte[] newArray = new byte[srcArray1.Length + srcArray2.Length];
                Array.Copy(srcArray1, 0, newArray, 0, srcArray1.Length);
                Array.Copy(srcArray2, 0, newArray, srcArray1.Length, srcArray2.Length);
                return newArray;
            }
    
    
            Thread tCheckLink;
            IPAddress ipAddr;
            IPEndPoint hostEP_Client;
            Socket socket_Client;
    
            FileTranser_Server fileTranser_Server = new FileTranser_Server();
    
            private void Link()
            {
                //判断 是否正在连接
                if (!fileTranser_Server.isConnected)
                {
                    //尝试 连接远程服务器
                    try
                    {
                        hostEP_Client = new IPEndPoint(ipAddr, 0368);
                        socket_Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        socket_Client.Connect(hostEP_Client);
                        fileTranser_Server.isConnected = true;
                    }
                    catch
                    {
                        MessageBox.Show("连接失败");
                        socket_Client.Close();
                        fileTranser_Server.isConnected = false;
                        return;
                    }
                }
                fileTranser_Server.isConnected = false;
                MessageBox.Show("连接成功");
                //激活 传送按钮
                setControlState();
            }
    
            private void Send()
            {
                //尝试 数据传送
                try
                {
                    string fileExt = "null";
                    //判断 连接是否中断
                    if (!fileTranser_Server.isConnected)
                    {
                        hostEP_Client = new IPEndPoint(ipAddr, 0368);
                        socket_Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        socket_Client.Connect(hostEP_Client);
                        fileTranser_Server.isConnected = true;
                    }
                    //声明 文件信息
                    byte[] fileArray;
                    //获取 文件路径
                    string filePath = tex_FilePath.Text.ToString();
                    string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
                    //打开 文件
                    FileStream FS = File.Open(filePath, FileMode.Open);
                    //获取 文件数据流
                    byte[] tmpdata = new byte[FS.Length];
                    FS.Read(tmpdata, 0, tmpdata.Length);
                    FS.Close();
                    //装填 文件扩展名
                    //区分 非空扩展名
                    if (fileName.LastIndexOf(".") != -1)
                        fileExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
                    byte[] fileExtArray = Encoding.UTF8.GetBytes(fileExt);
                    fileArray = fileExtArray;
                    //装填 文件扩展名长度
                    byte[] fileExtLeng = Encoding.UTF8.GetBytes(fileExtArray.Length.ToString("D1"));
                    fileArray = CombomBinaryArray(fileExtLeng, fileArray);
                    //装填 文件名
                    //区分 非空扩展名文件
                    if (fileName.LastIndexOf(".") != -1)
                        fileName = fileName.Substring(0, fileName.LastIndexOf("."));
                    byte[] fileNameArray = Encoding.UTF8.GetBytes(fileName);
                    fileArray = CombomBinaryArray(fileNameArray, fileArray);
                    //装填 文件名长度
                    byte[] fileNameLeng = Encoding.UTF8.GetBytes(fileNameArray.Length.ToString("D2"));
                    fileArray = CombomBinaryArray(fileNameLeng, fileArray);
                    //装填 数据流长度
                    byte[] fileLengArray = Encoding.UTF8.GetBytes(tmpdata.Length.ToString("D10"));
                    fileArray = CombomBinaryArray(fileArray, fileLengArray);
                    //组合 文件信息与文件数据流
                    byte[] fileData = CombomBinaryArray(fileArray, tmpdata);
                    //发送 文件包
                    socket_Client.Send(fileData, fileData.Length, 0);
                    //接收 反馈信息
                    string recvStr = "";
                    byte[] recvBytes = new byte[1024];
                    int bytes = 0;
                    while (true)
                    {
                        if (!fileTranser_Server.isConnected)
                        {
                            bytes = socket_Client.Receive(recvBytes, recvBytes.Length, 0);
                            recvStr = Encoding.UTF8.GetString(recvBytes);
                            MessageBox.Show(recvStr);
                            //关闭 socket
                            socket_Client.Shutdown(SocketShutdown.Both);
                            socket_Client.Close();
                        }
                    }
                }
                catch (Exception err)
                {
    
                }
            }
            private void Btn_Transmit_Click(object sender, EventArgs e)
            {
                if (string.IsNullOrEmpty(tex_FilePath.Text))
                {
                    MessageBox.Show("文件路径为空");
                    return;
                }
                //创建 线程进行数据传送
                Thread tTransmit = new Thread(Send);
                tTransmit.IsBackground = true;
                tTransmit.Start();
            }
    
            private void btn_Exit_Click(object sender, EventArgs e)
            {
                if(tCheckLink!=null)
                    tCheckLink.Abort();
                if (fileTranser_Server.tReceive != null)
                    fileTranser_Server.tReceive.Abort();
                fileTranser_Server.socket_Server.Dispose();
                fileTranser_Server.socket_Server.Close();
                fileTranser_Server.isConnected = true;
                this.Dispose(true);
                this.Close();
                Application.Exit();
            }
    
            private void btn_Select_Click(object sender, EventArgs e)
            {
                //打开 文件选择窗口
                OpenFileDialog openFile = new OpenFileDialog();
                //读取 配置文件
                string tmpPath = Environment.CurrentDirectory + "\\config.ini";
                FileStream fs = new FileStream(tmpPath, FileMode.OpenOrCreate);
                byte[] tmpStr = new byte[fs.Length];
                fs.Read(tmpStr, 0, tmpStr.Length);
                fs.Close();
                //设置 初始路径为配置文件内路径
                if (!string.IsNullOrEmpty(tmpStr.ToString()))
                {
                    openFile.InitialDirectory = tmpStr.ToString();
                }
                //设置 文件选择类型
                openFile.Filter = "All files(*.*)|*.*";
                openFile.FilterIndex = 1;
                openFile.RestoreDirectory = false;
                if (openFile.ShowDialog() == DialogResult.OK)
                {
                    //显示 所选路径
                    tex_FilePath.Text = openFile.FileName;
                    //记录 所选路径于配置文件
                    fs = new FileStream(tmpPath, FileMode.Open);
                    fs.Write(Encoding.UTF8.GetBytes(openFile.FileName), 0, openFile.FileName.Length);
                    fs.Close();
                }
            }
    
            private void onKeyPress(object sender, KeyPressEventArgs e)
            {
                Control actCtl = this.ActiveControl;
                Control nextCtl = this.GetNextControl(actCtl, true);
                Control lastCtl = this.GetNextControl(actCtl, false);
                //控制 输入字符
                if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
                {
                    e.Handled = true;
                }
                //自动 换栏
                if (actCtl != tex_IP4)
                {
                    if (e.KeyChar == '.')
                    {
                        nextCtl.Focus();
                        return;
                    }
                    if (actCtl.Text.Length == 3 && e.KeyChar != 8)
                    {
                        nextCtl.Text = "";
                        nextCtl.Focus();
                        SendKeys.Send(e.KeyChar.ToString());
                    }
                }
                if (e.KeyChar == 8 && string.IsNullOrEmpty(actCtl.Text))
                {
                    if (actCtl != tex_IP1)
                    {
                        lastCtl.Focus();
                    }
                }
                if (e.KeyChar == 13)
                {
                    btn_Check_Click(sender, e);
                }
            }
    
            private void btn_Check_Click(object sender, EventArgs e)
            {
                IPAddress[] ipPool = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
                lab_Hint.Visible = false;
                string tmpIP = null;
                //判断 文本框是否为空
                foreach (Control ip in pan_IP.Controls)
                {
                    if (string.IsNullOrEmpty(ip.Text))
                    {
                        MessageBox.Show("第" + ip.Name.ToString().Substring(ip.Name.ToString().IndexOf("P") + 1) + "段IP为空");
                        ip.Focus();
                        return;
                    }
                    //组合 IP地址
                    tmpIP += ip.Text;
                    if (ip != tex_IP4)
                        tmpIP += ".";
                }
                ipAddr = IPAddress.Parse(tmpIP);
                //创建 线程连接
                tCheckLink = new Thread(Link);
                tCheckLink.IsBackground = true;
                tCheckLink.Start();
            }
    
            private void tex_IP_TextChanged(object sender, EventArgs e)
            {
                btn_Transmit.Enabled = false;
                lab_Hint.Visible = true;
                lab_Hint.Text = "IP地址已更改,请点击Check按钮检查连接是否通畅!";
            }
        }
        public partial class FileTranser_Server
        {
            public bool isConnected = false;
            //创建 socket
            public Socket socket_Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            public Thread tReceive;
    
            public void fileReceive()
            {
                while (true)
                {
                    if (isConnected)
                    {
                        //创建 socket
                        Socket client = socket_Server.Accept();
                        //初始 变量
                        byte[] recvBytes = new byte[1024];
                        int bytes = 0;
                        int fileLength = 0;
                        int receivedLength = 0;
                        int fileNameLeng = 0;
                        int fileExtLeng = 0;
                        //接收 文件名长度
                        bytes = client.Receive(recvBytes, 2, 0);
                        fileNameLeng = Convert.ToInt32(Encoding.UTF8.GetString(recvBytes, 0, bytes));
                        //接收 文件名
                        bytes = client.Receive(recvBytes, fileNameLeng, 0);
                        string fileName = Encoding.UTF8.GetString(recvBytes, 0, bytes);
                        //MessageBox.Show(fileName);
                        //接收 文件扩展名长度
                        bytes = client.Receive(recvBytes, 1, 0);
                        fileExtLeng = Convert.ToInt32(Encoding.UTF8.GetString(recvBytes, 0, bytes));
                        //MessageBox.Show(fileExtLeng.ToString());
                        //接收 文件扩展名
                        bytes = client.Receive(recvBytes, fileExtLeng, 0);
                        string fileExt = Encoding.UTF8.GetString(recvBytes, 0, bytes);
                        //MessageBox.Show(fileExt);
                        //接收 数据流长度
                        bytes = client.Receive(recvBytes, 10, 0);
                        //MessageBox.Show(Encoding.UTF8.GetString(recvBytes, 0, bytes));
                        fileLength = Convert.ToInt32(Encoding.UTF8.GetString(recvBytes, 0, bytes));
                        //组合 文件存放路径
                        string filePath = Environment.CurrentDirectory + "\\" + fileName;
                        if (fileExt != "null")
                            filePath += "." + fileExt;
                        //创建 文件
                        FileStream fileStream = new FileStream(filePath, FileMode.Create);
                        //接收 数据流
                        while (receivedLength < fileLength)
                        {
                            bytes = client.Receive(recvBytes, recvBytes.Length, 0);
                            receivedLength += bytes;
                            fileStream.Write(recvBytes, 0, bytes);
                        }
                        //释放 数据流资源
                        fileStream.Flush();
                        fileStream.Close();
                        //反馈 文件传输完成状态
                        string reData = "File\n" + filePath.Substring(filePath.LastIndexOf("\\") + 1) + "\nTransmit success!";
                        byte[] reByte = Encoding.UTF8.GetBytes(reData);
                        client.Send(reByte, reByte.Length, 0);
                        //释放 socket
                        client.Shutdown(SocketShutdown.Both);
                        client.Close();
                        isConnected = false;
                    }
                }
            }
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!