예제 #1
0
        /// <summary>
        /// 大文件断点传送
        /// </summary>
        private void SendBigFile(Object _socketModel)
        {
            SocketSendModel socketModel = (SocketSendModel)_socketModel;
            Socket          socketSend  = socketModel.socketSend;
            String          filePath    = socketModel.strSend;

            try
            {
                //读取选择的文件
                using (FileStream fsRead = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read))
                {
                    //1. 第一步:发送一个包,表示文件的长度,让客户端知道后续要接收几个包来重新组织成一个文件
                    long   length     = fsRead.Length;
                    byte[] byteLength = Encoding.UTF8.GetBytes(length.ToString());
                    //获得发送的信息时候,在数组前面加上一个字节 1
                    List <byte> list = new List <byte>();
                    list.Add(1);
                    list.AddRange(byteLength);
                    socketSend.Send(list.ToArray()); //
                    //2. 第二步:每次发送一个1MB的包,如果文件较大,则会拆分为多个包
                    byte[] buffer = new byte[1024 * 1024];
                    long   send   = 0; //发送的字节数
                    while (true)       //大文件断点多次传输
                    {
                        int r = fsRead.Read(buffer, 0, buffer.Length);
                        if (r == 0)
                        {
                            break;
                        }
                        socketSend.Send(buffer, 0, r, SocketFlags.None);
                        send += r;
                        ShowMsg(string.Format("{0}: 已发送:{1}/{2}", socketSend.RemoteEndPoint, send, length));
                    }
                    ShowMsg("发送完成");
                }
            }
            catch
            {
            }
        }
예제 #2
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="conection"></param>
        /// <param name="msg"></param>
        public void SendMsg(Object _socketModel)
        {
            try
            {
                SocketSendModel socketModel = (SocketSendModel)_socketModel;
                Socket          socketSend  = socketModel.socketSend;
                String          strSend     = socketModel.strSend;

                byte[] buffer = Encoding.UTF8.GetBytes(strSend);
                //获得发送的信息时候,在数组前面加上一个字节 0
                List <byte> list = new List <byte>();
                list.Add(0);
                list.AddRange(buffer);
                //将泛型集合转换为数组
                byte[] newBuffer = list.ToArray();
                //将了标识字符的字节数组传递给客户端
                socketSend.Send(newBuffer);
            }
            catch
            {
            }
        }