Пример #1
0
 /// <summary>
 /// 发送一个数据库操作请求。如果发送成功返回true,否则返回false
 /// </summary>
 /// <param name="userModel">用户对象</param>
 /// <param name="operation">操作类型</param>
 /// <param name="parameter">操作参数</param>
 public bool SendDatabaseRequest(User user, string operation, string parameter)
 {
     if (ClientState)
     {
         byte[] buffer = BytesConvert.ObjectToBytes(new Transmit()
         {
             SourceID  = ClientID,
             TargetID  = ClientID,
             DataType  = DataType.Request,
             Parameter = $"Database;{operation},{parameter}",
             Object    = user
         });
         SocketAsyncEventArgs args = new SocketAsyncEventArgs();
         try
         {
             args.SetBuffer(buffer, 0, buffer.Length);
             clientSocket.SendAsync(args);
             return(true);
         }
         catch (Exception exception)
         {
             ClientError?.Invoke(this, new ClientErrorEventArgs(exception, "在发送请求时发生错误"));
         }
         finally
         {
             args.Dispose();
         }
     }
     return(false);
 }
Пример #2
0
        public void Start(string host_address, ushort host_port)
        {
            _ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            bool join = false;

            try
            {
                _ClientSocket.Connect(host_address, host_port);

                join = true;
            }
            catch (Exception ex)
            {
                ClientError?.Invoke(new ClientErrorEventArgs(ex, DateTime.Now, this));

                join = false;
            }

            _Connected = join;

            if (join)
            {
                AsyncObject ao = new AsyncObject(4096);
                ao.WorkingSocket = _ClientSocket;
                _ClientSocket.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnReceive, ao);
            }
        }
Пример #3
0
 /// <summary>
 /// 异步的发送文本消息。如果发送成功返回true,否则返回false
 /// </summary>
 /// <param name="targetUserID">目标用户ID</param>
 /// <param name="message">文本消息</param>
 public async Task <bool> SendTextAsync(string targetUserID, string message)
 {
     if (ClientState && targetUserID != null && message != null)
     {
         return(await Task.Run <bool>(() =>
         {
             byte[] buffer = BytesConvert.ObjectToBytes(new Transmit()
             {
                 SourceID = ClientID,
                 TargetID = targetUserID,
                 DataType = DataType.Text,
                 Parameter = message
             });
             try
             {
                 clientSocket.Send(buffer, buffer.Length, SocketFlags.None);
                 return true;
             }
             catch (Exception exception)
             {
                 ClientError?.Invoke(this, new ClientErrorEventArgs(exception, "在发送文本消息时发生错误"));
                 return false;
             }
         }));
     }
     return(false);
 }
Пример #4
0
        private void send(IAsyncResult ar)
        {
            AsyncObject ao = (AsyncObject)ar.AsyncState;

            int sendBytes;

            try
            {
                sendBytes = ao.WorkingSocket.EndSend(ar);
            }
            catch (Exception ex)
            {
                ClientError?.Invoke(new ClientErrorEventArgs(ex, DateTime.Now, this));

                return;
            }

            if (sendBytes > 0)
            {
                byte[] msgByte = new byte[sendBytes];
                Array.Copy(ao.Buffer, msgByte, sendBytes);

                Message msg = new Message(msgByte);

                SendMessage?.Invoke(new MessageEventArgs(msg, ao.WorkingSocket));
            }
        }
Пример #5
0
 /// <summary>
 /// 异步的发送图片。如果发送成功返回true,否则返回false
 /// </summary>
 /// <param name="targetUserID">目标ID</param>
 /// <param name="imagePath">图片路径</param>
 public async Task <bool> SendImageAsync(string targetUserID, string imagePath)
 {
     if (ClientState && targetUserID != null && imagePath != null)
     {
         return(await Task.Run <bool>(() =>
         {
             FileStream fileStream = null;              //文件流
             byte[] dataBuffer = new byte[1024 * 1024]; //数据缓冲区
             try
             {
                 fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
                 if (fileStream.Length == 0)
                 {
                     return false;
                 }
                 byte[] buffer = BytesConvert.ObjectToBytes(new Transmit()
                 {
                     SourceID = ClientID,
                     TargetID = targetUserID,
                     DataType = DataType.Image,
                     Parameter = $"{Path.GetFileName(imagePath)};{fileStream.Length}"
                 });
                 clientSocket.Send(buffer, buffer.Length, SocketFlags.None);
                 Thread.Sleep(100);
                 while (true)
                 {
                     int readBytes = fileStream.Read(dataBuffer, 0, dataBuffer.Length);
                     if (readBytes <= 0)
                     {
                         break;
                     }
                     clientSocket.Send(dataBuffer, readBytes, SocketFlags.None);
                     Thread.Sleep(10);
                 }
             }
             catch (Exception exception)
             {
                 ClientError?.Invoke(this, new ClientErrorEventArgs(exception, "在发送图片时发生错误"));
                 return false;
             }
             finally
             {
                 fileStream?.Close();
                 fileStream?.Dispose();
                 fileStream = null;
             }
             return true;
         }));
     }
     return(false);
 }
Пример #6
0
        /// <summary>
        /// 异步的连接服务器。如果连接成功返回true,否则返回false
        /// </summary>
        public async Task <bool> ConnectionServerAsync()
        {
            if (ClientState)
            {
                return(await Task.Run <bool>(() =>
                {
                    ClientMessage?.Invoke(this, new ClientNotifyEventArgs("正在建立与服务器的连接"));
                    try
                    {
                        clientSocket.Connect(ServerIPEndPoint);
                        byte[] checkBuffer = new byte[1] {
                            0
                        };
                        clientSocket.Send(Encoding.UTF8.GetBytes(ClientID));
                        if (clientSocket.Poll(15000000, SelectMode.SelectRead))
                        {
                            clientSocket.Receive(checkBuffer);
                            if (checkBuffer[0] != 1)
                            {
                                ClientMessage?.Invoke(this, new ClientNotifyEventArgs("服务器拒绝连接"));
                                return false;
                            }
                        }
                        else
                        {
                            ClientMessage?.Invoke(this, new ClientNotifyEventArgs("服务器连接超时"));
                            return false;
                        }
                    }
                    catch (Exception exception)
                    {
                        ClientMessage?.Invoke(this, new ClientNotifyEventArgs("无法连接到服务器"));
                        ClientError?.Invoke(this, new ClientErrorEventArgs(exception, "无法连接到服务器"));
                        return false;
                    }
                    switch (ClientAgreement)
                    {
                    case ProtocolType.Tcp:
                        Task task = Task.Run(MainReceiver);
                        break;

                    case ProtocolType.Udp:
                        break;
                    }
                    ClientMessage?.Invoke(this, new ClientNotifyEventArgs("服务器连接成功"));
                    return true;
                }));
            }
            return(false);
        }
Пример #7
0
        public void ProcessError(Exception e_, string message = null)
        {
            mLastError = e_;
            ClientErrorArgs e = new ClientErrorArgs();

            e.Error   = e_;
            e.Message = message;
            try
            {
                ClientError?.Invoke(this, e);
            }
            catch
            {
            }
        }
Пример #8
0
        public void Send(Message message)
        {
            AsyncObject ao = new AsyncObject(1);

            ao.Buffer        = message;
            ao.WorkingSocket = _ClientSocket;

            try
            {
                _ClientSocket.BeginSend(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnSend, ao);
            }
            catch (Exception ex)
            {
                ClientError?.Invoke(new ClientErrorEventArgs(ex, DateTime.Now, this));
            }
        }
Пример #9
0
        private void onError(object sender, ExceptionEventArgs e)
        {
            int index = clients.IndexOf((ServerClient)sender);

            if (index < 0)
            {
                return;
            }

            lock (lockObj) {
                clients.RemoveAt(index);
            }

            ClientError?.Invoke(this, new ListExceptionEventArgs(index, e.Exception));

            ((ServerClient)sender).Disconnect();
        }
Пример #10
0
        public void ProcessError(Exception e_, string message = null)
        {
            mLastError = e_;
            ClientErrorArgs e = new ClientErrorArgs();

            e.Error   = e_;
            e.Message = message;
            try
            {
                //if (awaitPipeStream.Pending)
                //    awaitPipeStream.Error(e_);
                //if (mReadMessageAwait.Pending)
                //    mReadMessageAwait.Error(e_);
                ClientError?.Invoke(this, e);
            }
            catch
            {
            }
        }
Пример #11
0
        private void receive(IAsyncResult ar)
        {
            AsyncObject ao = (AsyncObject)ar.AsyncState;

            int recvBytes = 0;

            try
            {
                recvBytes = ao.WorkingSocket.EndReceive(ar);
            }
            catch (Exception ex)
            {
                ClientError?.Invoke(new ClientErrorEventArgs(ex, DateTime.Now, this));

                return;
            }

            if (recvBytes > 0)
            {
                byte[] msgByte = new byte[recvBytes];
                Array.Copy(ao.Buffer, msgByte, recvBytes);

                Message msg = new Message(msgByte);

                ReceiveMessage?.Invoke(new MessageEventArgs(msg, ao.WorkingSocket));
            }

            try
            {
                ao.WorkingSocket.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnReceive, ao);
            }
            catch (Exception ex)
            {
                ClientError?.Invoke(new ClientErrorEventArgs(ex, DateTime.Now, this));

                return;
            }
        }
Пример #12
0
        public void ProcessError(Exception e_, string message = null)
        {
            mLastError = e_;
            ClientErrorArgs e = new ClientErrorArgs();

            e.Error   = e_;
            e.Message = message;
            try
            {
                if (awaitPipeStream.Pending)
                {
                    awaitPipeStream.Error(e_);
                }
                if (mReadMessageAwait.Pending)
                {
                    mReadMessageAwait.Error(e_);
                }
                ClientError?.Invoke(this, e);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Пример #13
0
        // Dunno if sender should really be null for the event invocations, but I can't use this 'cause static class, so....

        internal static void InvokeClientError(ClientErrorArgs args)
        {
            ClientError?.Invoke(null, args);
        }
Пример #14
0
 protected virtual void OnClientError(ErrorEventArgs e)
 {
     ClientError?.Invoke(this, e);
 }
Пример #15
0
        /// <summary>
        /// 主接收器
        /// </summary>
        private void MainReceiver()
        {
            byte[] dataBuffer = new byte[1024 * 1024]; //数据缓冲区

            bool     isFirstReceive = true;            //是否为首次接收数据
            Transmit transmit       = null;            //传输对象
            double   dataSize       = 0.0;             //数据总大小
            double   receiveBytes   = 0.0;             //已接收的字节数

            while (true)
            {
                int readBytes = 0;
                if (clientSocket.Poll(-1, SelectMode.SelectRead))
                {
                    if (!ClientState)
                    {
                        break;
                    }
                    try
                    {
                        readBytes = clientSocket.Receive(dataBuffer, dataBuffer.Length, SocketFlags.None);
                        if (readBytes == 0)
                        {
                            CloseClient();
                            ClientMessage?.Invoke(this, new ClientNotifyEventArgs("服务器断开连接"));
                            break;
                        }
                    }
                    catch (Exception exception)
                    {
                        CloseClient();
                        ClientMessage?.Invoke(this, new ClientNotifyEventArgs("服务器断开连接"));
                        ClientError?.Invoke(this, new ClientErrorEventArgs(exception, "服务器意外的断开连接"));
                        break;
                    }
                }

                //首次接收数据
                if (isFirstReceive)
                {
                    isFirstReceive = false;
                    transmit       = BytesConvert.BytesToObject(dataBuffer, readBytes, "MiniSocket.Transmitting") as Transmit;
                    if (transmit?.Parameter != null)
                    {
                        switch (transmit.DataType)
                        {
                        case DataType.Text:
                            ReceiveDataHandler(transmit, null, 0);
                            break;

                        case DataType.Image:
                            string[] parameters = transmit.Parameter.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                            if (parameters.Length == 2)
                            {
                                if (double.TryParse(parameters[1], out dataSize))
                                {
                                    continue;
                                }
                            }
                            break;

                        case DataType.Request:
                            ReceiveRequestHandler(transmit);
                            break;
                        }
                    }
                    ResetParameter(ref isFirstReceive, ref transmit, ref dataSize, ref receiveBytes);
                    continue;
                }

                receiveBytes += readBytes; //已接收到的数据累加

                //判断已接收到的数据是否有效
                if (receiveBytes > 0 && receiveBytes <= dataSize)
                {
                    ReceiveDataHandler(transmit, dataBuffer, readBytes);
                }
                //判断是否接收完成或数据是否有误
                if (receiveBytes == dataSize || (receiveBytes <= 0 || receiveBytes > dataSize))
                {
                    ResetParameter(ref isFirstReceive, ref transmit, ref dataSize, ref receiveBytes);
                    continue;
                }
            }
        }
Пример #16
0
        /// <summary>
        /// 异步的发送文件。如果发送成功返回true,否则返回false
        /// </summary>
        /// <param name="targetUserID">目标ID</param>
        /// <param name="filePath">文件路径</param>
        public async Task <bool> SendFileAsync(string targetUserID, string filePath)
        {
            if (ClientState && targetUserID != null && filePath != null)
            {
                return(await Task.Run <bool>(async() =>
                {
                    FileStream fileStream = null;              //文件流
                    byte[] dataBuffer = new byte[1024 * 1024]; //数据缓冲区
                    try
                    {
                        fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                        if (fileStream.Length == 0)
                        {
                            return false;
                        }
                        byte[] buffer = BytesConvert.ObjectToBytes(new Transmit()
                        {
                            SourceID = ClientID,
                            TargetID = targetUserID,
                            DataType = DataType.File,
                            Parameter = $"{Path.GetFileName(filePath)};{fileStream.Length}"
                        });
                        SocketResult socketResult = await socketManager.CreateConnectionAsync();
                        switch (socketResult.State)
                        {
                        case ConnectionState.Success:
                            socketResult.Socket.Send(buffer, buffer.Length, SocketFlags.None);
                            break;

                        case ConnectionState.Failed:
                            throw new ArgumentException("服务器拒绝连接");

                        case ConnectionState.Timeout:
                            throw new ArgumentException("服务器连接超时");

                        case ConnectionState.Error:
                            throw socketResult.Exception;
                        }
                        Thread.Sleep(5000);
                        while (true)
                        {
                            int readBytes = fileStream.Read(dataBuffer, 0, dataBuffer.Length);
                            if (readBytes <= 0)
                            {
                                break;
                            }
                            socketResult.Socket.Send(dataBuffer, readBytes, SocketFlags.None);
                            Thread.Sleep(10);
                        }
                    }
                    catch (Exception exception)
                    {
                        ClientError?.Invoke(this, new ClientErrorEventArgs(exception, "在发送文件时发生错误"));
                        return false;
                    }
                    finally
                    {
                        fileStream?.Close();
                        fileStream?.Dispose();
                        fileStream = null;
                    }
                    return true;
                }));
            }
            return(false);
        }