C# soket传输文件

服务器端数据SQLServer查出转存SQLite
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Data.SQLite;
using System.Configuration;
using System.IO;
using System.IO.Compression;
using System.Threading;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.BZip2;
namespace Sockets
{
    public partial class ServerForm : Form
    {
        Socket s = null;
        IPEndPoint iep = null;
        byte[] buf = new byte[5000];
        Socket worker = null;

        private SQLiteCommand comma;
        private SQLiteConnection sqc;

        public ServerForm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        #region 打开sqlite数据库
        /// <summary>
        /// 打开数据库
        /// </summary>
        private void opensqlite() //打开sqlite数据库
        {
            sqc = new System.Data.SQLite.SQLiteConnection("Data Source=C:\\Documents and Settings\\fei5280\\桌面\\Sockets\\XMLs\\barcodetp.db;Pooling=false;FailIfMissing=false");
            sqc.Open();
            comma = sqc.CreateCommand();
        }
        #endregion

        #region 查询插入数据
        /// <summary>
        /// 数据操作
        /// </summary>
        private void getdata()
        {
            int iCount = 0;
            StringBuilder str = new StringBuilder();
            comma.CommandText = "delete from barlabel";
            comma.ExecuteNonQuery();
            string sqlstr = "SELECT TOP 10000 a.barcode,b.lot_no,a.packing_no,a.grade,a.nwt FROM barcodes.dbo.barin a INNER JOIN hc.dbo.specinfo b ON a.prod_id=b.prod_id";
            DataTable dt = new Sysmis.Data.eTable("bars").Execute(sqlstr);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                str.Append("INSERT INTO barlabel values('" + dt.Rows[i]["barcode"].ToString() + "','" + dt.Rows[i]["lot_no"].ToString() + "','" + dt.Rows[i]["packing_no"].ToString() + "','" + dt.Rows[i]["grade"].ToString() + "','" + dt.Rows[i]["nwt"].ToString() + "');");
                //str.Append("INSERT INTO barstore values('" + dt.Rows[i]["barcode"].ToString() + "');");
                iCount = iCount + 1;
                if (iCount > 500)
                {
                    comma.CommandText = "BEGIN TRANSACTION;" + str.ToString() + "COMMIT;";
                    //};
                    comma.ExecuteNonQuery();
                    str.Remove(0, str.Length);
                    iCount = 0;
                }
            }
            comma.CommandText = "BEGIN TRANSACTION;" + str.ToString() + "COMMIT;";
            int j = comma.ExecuteNonQuery();
            comma.Dispose();
            sqc.Dispose();
            sqc.Close();

        }
        #endregion

        #region 打开SOCKET TCP通道
        private void button1_Click(object sender, EventArgs e)
        {
            //创建一个通道
            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //创建一个侦听点
            iep = new IPEndPoint(IPAddress.Any, 20000);
            //绑定到通道上
            s.Bind(iep);
            //侦听
            s.Listen(6);
            //通过异步来处理
            s.BeginAccept(new AsyncCallback(Accept), s);
            this.button1.Visible = false;
        }
        #endregion

        #region 处理接收到的消息
        void Accept(IAsyncResult ia)
        {
            s = ia.AsyncState as Socket;
            worker = s.EndAccept(ia);
            s.BeginAccept(new AsyncCallback(Accept), s);
            try
            {
                //检查是否有客户端发送来的操作消息 异步调用
                worker.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(Receive), worker);
            }
            catch
            { throw; }
        }
        #endregion

        #region  接收发送消息
        /// <summary>
        /// 当客户端接收到特定的信息的时候自动发送文件barcodetp.db
        /// </summary>
        /// <param name="ia"></param>
        void Receive(IAsyncResult ia)
        {
            try
            {
                opensqlite();
                getdata();
                worker = ia.AsyncState as Socket;  //原本的Socket对象使用用来接收信息,每收到一次,都会创建一个包含该条信息的Socket对象,你只能通过这个创建出来的Socket对象来收取信息,而那个最初的Socket对象只负责接收。
                int count = worker.EndReceive(ia); //结束时挂起异步读取
                worker.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(Receive), worker);
                //buf =  ReceiveVarData(worker);

                string context = Encoding.GetEncoding("gb2312").GetString(buf, 0, count);
                this.textBox1.Text += Environment.NewLine;
                this.textBox1.Text += context;
                if (this.textBox1.Text != "")
                {
                    FileStream sr = null;
                    byte[] buffer = null;
                    string path = "C:\\Documents and Settings\\fei5280\\桌面\\Sockets\\XMLs\\barcodetp.db";
                    if (File.Exists(path))
                    {
                        FileInfo EzoneFile = new FileInfo(path);
                        sr = EzoneFile.OpenRead(); //获得读取的FileStream
                        buffer = new byte[sr.Length];  //sr.Length 获得文件的大小 1kb文件 = new byte[1024]; 
                    }
                    else
                    {
                        MessageBox.Show("无法找到文件");
                        return;
                    }
                    //发送[包的大小]到客户端
                    SendVarData(worker, Encoding.GetEncoding("gb2312").GetBytes(sr.Length.ToString()));
                    byte[] data = null;
                    //包的数量
                    int aaa = (int)buffer.Length / 5000;
                    //开始循环发送数据包
                    for (int i = 0; i < aaa; i++)
                    {
                        //从文件流读取数据并填充数据包
                        sr.Read(buf, 0, buf.Length);
                        //发送数据包
                        SendVarData(worker, buf);
                        //显示发送数据包的个数
                    }
                    //未被发送完成的包的数量
                    int bbb = buffer.Length - aaa * 5000;
                    //如果还有多余的数据包,则应该发送完毕!
                    if (bbb != 0)
                    {
                        data = new byte[bbb];
                        sr.Read(data, 0, data.Length);
                        SendVarData(worker, data);
                        // this.progressBar1.Value = this.progressBar1.Maximum;
                    }
                    sr.Flush();
                    sr.Close();
                    // worker.Send(buffer);
                }
            }
            catch
            {

            }
        }
        #endregion

        #region 服务端发送数据的方法(最好不要调用) 客户端可能报错
        private void button2_Click(object sender, EventArgs e)
        {
            string context = "XXXXX" + this.textBox2.Text.Trim();
            if (context != "")
            {
                this.textBox1.Text += Environment.NewLine;
                this.textBox1.Text += context;
                this.textBox2.Text = "";
                worker.Send(Encoding.GetEncoding("gb2312").GetBytes(context));
            }
        }
        #endregion

        #region 循环发送数据
        /// <summary>
        /// 循环传输数据
        /// </summary>
        /// <param name="s"></param>
        /// <param name="data"></param>
        /// <returns>传输数据的数量</returns>
        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];
            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;
        }
        #endregion

        #region 循环接收数据
        public byte[] ReceiveVarData(Socket s)
        {
            int recv = 1;
            int total = 0;

            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);
                total += recv;
                dataleft -= recv;
            }
            return data;
        }
        #endregion

        #region   压缩
        public static byte[] Compress(byte[] byteArray)
        {
            //byte[] byteArray = Encoding.UTF8.GetBytes(value); ------当传入为string时
            byte[] tmpArray;

            using (MemoryStream ms = new MemoryStream())
            {
                using (GZipStream sw = new GZipStream(ms, CompressionMode.Compress))
                {
                    sw.Write(byteArray, 0, byteArray.Length);
                    sw.Flush();
                }
                tmpArray = ms.ToArray();
            }
            return tmpArray;
        }
        #endregion

        #region   解压缩
        /// <summary>
        /// 解压缩
        /// </summary>
        /// <param name="value1"></param>
        /// <returns></returns>
        public static byte[] Decompress(byte[] value1)
        {
            //byte[] zippedData = Convert.FromBase64String(value1);  -----当传入为string时
            MemoryStream ms = new MemoryStream(value1);

            GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress);
            MemoryStream outBuffer = new MemoryStream();
            byte[] block = new byte[1024];
            while (true)
            {
                int bytesRead = compressedzipStream.Read(block, 0, block.Length);
                if (bytesRead <= 0)
                    break;
                else
                    outBuffer.Write(block, 0, bytesRead);
            }
            compressedzipStream.Close();
            return outBuffer.ToArray();
        }
        #endregion

        #region 窗口关闭
        public void ServerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Dispose();
        }
        #endregion

        public static byte[] Zip(byte[] data)
        {
            MemoryStream inStream = new MemoryStream(data);
            MemoryStream outStream = new MemoryStream();
            BZip2.Compress(inStream, outStream, data.Length);
            byte[] result = outStream.ToArray();
            inStream.Close();
            outStream.Close();

            return result;
        }

        public static byte[] Unzip(byte[] data, int offset, int size)
        {
            MemoryStream inStream = new MemoryStream(data, offset, size);
            MemoryStream outStream = new MemoryStream();
            BZip2.Decompress(inStream, outStream);
            byte[] result = outStream.ToArray();
            inStream.Close();
            outStream.Close();
            return result;
        }
    }
}

客户端(winCE通用)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using ICSharpCode.SharpZipLib.BZip2;
using System.Threading;

namespace Sockets
{
    public partial class ClientForm : Form
    {

        Socket s = null;
        IPEndPoint iep = null;
        private int bagCount;
        private string path = "E:\\barcodelot1.db";
        public ClientForm()
        {
            InitializeComponent();
            // Control.CheckForIllegalCrossThreadCalls = false;
        }

        #region 连接服务器端
        private void button1_Click(object sender, EventArgs e)
        {
            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            iep = new IPEndPoint(IPAddress.Parse("192.168.10.24"), 20000);
            try
            {
                s.Connect(iep);
                this.label1.Text = "连接成功";
                this.button1.Visible = false;
            }
            catch
            { throw; }
        }
        #endregion

        #region 发送消息 接收服务端传输过来的文件
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {

            this.label3.Visible = true;
            this.label3.Text = "数据准备中.......";
            Application.DoEvents();
            this.button2.Enabled = false;
            string context = iep.ToString() + ":" + this.textBox2.Text.Trim();
            //this.textBox1.Text += Environment.NewLine;
            this.textBox1.Text += context;
            this.textBox2.Text = "";
           
            //if (File.Exists(path))
            //{
            //    File.Delete(path);
            //}
            //发送数据的到服务器端
            s.Send(Encoding.GetEncoding("gb2312").GetBytes("s42160144295"));
            //新建服务器端传输的文件
            FileStream MyFileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
            // int SendedCount = 0;
            //接收到服务器端传输的文件大小
            byte[] bu = ReceiveVarData(s);
            bagCount = int.Parse(Encoding.GetEncoding("gb2312").GetString(bu, 0, bu.Length));
            this.progressBar1.Maximum = bagCount;

            while (true)
            {
                this.progressBar1.Visible = true;
                this.label2.Visible = true;
                this.label3.Visible = false;
                Application.DoEvents();
                this.label2.Text = (Convert.ToDouble(MyFileStream.Length) / Convert.ToDouble(bagCount)).ToString("P"); ;
                this.progressBar1.Value = Convert.ToInt32(MyFileStream.Length);
                if (MyFileStream.Length >= bagCount)
                {
                    this.label2.Text = "100 %";
                    this.progressBar1.Value = this.progressBar1.Maximum;
                    break;
                }
                byte[] data = ReceiveVarData(s);
                //  SendedCount++;
                //将接收到的数据包写入到文件流对象
                MyFileStream.Write(data, 0, data.Length);
                //显示已发送包的个数
                //MessageBox.Show("已发送包个数"+SendedCount.ToString());
            }
            //关闭文件流
            MyFileStream.Flush();
            MyFileStream.Close();
            MessageBox.Show("OK");
            this.progressBar1.Value = 0;
            this.label2.Text = "0 %";
            this.button2.Enabled = true;
            this.progressBar1.Visible =false;
            this.label2.Visible = false;

        }
        #endregion



        #region 循环接收数据
        public byte[] ReceiveVarData(Socket s)
        {
            int recv = 1;
            int total = 0;

            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);
                total += recv;
                dataleft -= recv;
            }
            return data;
        }
        #endregion

        //#region 解压缩 暂未用到
        //public byte[] Decompress(byte[] value1)
        //{
        //    //byte[] zippedData = Convert.FromBase64String(value1);
        //    MemoryStream ms = new MemoryStream(value1);
        //    GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress);
        //    MemoryStream outBuffer = new MemoryStream();
        //    byte[] block = new byte[1024];
        //    while (true)
        //    {
        //        int bytesRead = compressedzipStream.Read(block, 0, block.Length);
        //        if (bytesRead <= 0)
        //        {
        //            break;
        //        }
        //        else
        //            outBuffer.Write(block, 0, bytesRead);
        //    }
        //    compressedzipStream.Close();
        //    return outBuffer.ToArray();
        //}
        //#endregion

        //#region 关闭窗口
        //public void ClientForm_FormClosing(object sender, FormClosingEventArgs e)
        //{
        //    this.Dispose();
        //}
        //#endregion


        public static byte[] Unzip(byte[] data)
        {
            MemoryStream inStream = new MemoryStream(data);
            MemoryStream outStream = new MemoryStream();
            BZip2.Decompress(inStream, outStream);

            byte[] result = outStream.ToArray();
            inStream.Close();
            outStream.Close();
            return result;
        }

    }
}

你可能感兴趣的:(C#,Scoket,WinCE)