Ejemplo n.º 1
0
        private HandleResult OnReceive(HPSocketCS.TcpClient sender, IntPtr pData, int length)
        {
            try
            {
                //获取消息

                if (length == 0)
                {
                    this.Dispose();
                    return(HandleResult.Error);
                }

                byte[] data = new byte[length];
                Marshal.Copy(pData, data, 0, length);

                recbuffer.Add(data);
                StatisticsManage.AddReceiveBytes(length);
                ProcessReceive();
            }
            catch (Exception)
            {
                this.Dispose();
                return(HandleResult.Error);
            }

            return(HandleResult.Ok);
        }
Ejemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bufferSize"></param>
        public PipelineSocket(int bufferSize)
        {
            this.bufferSize = bufferSize;
            socket          = new HPSocketCS.TcpClient();

            SetListener();
        }
Ejemplo n.º 3
0
 private HandleResult OnSend(HPSocketCS.TcpClient sender, IntPtr pData, int length)
 {
     //Interlocked.CompareExchange(ref _isSend, 0, 1);
     //if (sendbuffer.Count > 0)
     //{
     //    ProcessSend();
     //}
     return(HandleResult.Ok);
 }
Ejemplo n.º 4
0
        static HandleResult OnClose(TcpClient sender)
        {
            // 连接关闭了

            AddMsg(string.Format(" > [{0},OnClose]", sender.ConnectionId));

            // 通知界面
            //this.Invoke(new SetAppStateDelegate(SetAppState), AppState.Stoped);
            return HandleResult.Ok;
        }
Ejemplo n.º 5
0
        static HandleResult OnError(TcpClient sender, SocketOperation enOperation, int errorCode)
        {
            // 出错了

            AddMsg(string.Format(" > [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));

            // 通知界面,只处理了连接错误,也没进行是不是连接错误的判断,所以有错误就会设置界面
            // 生产环境请自己控制
            //this.Invoke(new SetAppStateDelegate(SetAppState), AppState.Stoped);

            return HandleResult.Ok;
        }
Ejemplo n.º 6
0
        public TcpClientEx(String sIP, ushort nPort, int reconnectTime, OnSocket onSocket)
        {
            m_sIP            = sIP;
            m_nPort          = nPort;
            m_nReconnectTime = reconnectTime;
            m_OnSocket       = onSocket;

            m_TcpClient     = new HPSocketCS.TcpClient();
            m_bStartConnect = m_bConnect = false;
            m_LockObject    = new object();

            m_Queue     = new Queue <ClientSocketEvent>();
            m_TempQueue = new Queue <ClientSocketEvent>();

            m_TcpClient.OnPrepareConnect += new TcpClientEvent.OnPrepareConnectEventHandler(OnPrepareConnect);
            m_TcpClient.OnConnect        += new TcpClientEvent.OnConnectEventHandler(OnConnect);
            m_TcpClient.OnSend           += new TcpClientEvent.OnSendEventHandler(OnSend);
            m_TcpClient.OnReceive        += new TcpClientEvent.OnReceiveEventHandler(OnReceive);
            m_TcpClient.OnClose          += new TcpClientEvent.OnCloseEventHandler(OnClose);
        }
Ejemplo n.º 7
0
        public bool ReConnect(String sIP, int nPort)
        {
            if (m_TcpClient != null)
            {
                m_TcpClient.Destroy();
            }

            m_TcpClient = new HPSocketCS.TcpClient();
            m_TcpClient.OnPrepareConnect += new TcpClientEvent.OnPrepareConnectEventHandler(OnPrepareConnect);
            m_TcpClient.OnConnect        += new TcpClientEvent.OnConnectEventHandler(OnConnect);
            m_TcpClient.OnSend           += new TcpClientEvent.OnSendEventHandler(OnSend);
            m_TcpClient.OnReceive        += new TcpClientEvent.OnReceiveEventHandler(OnReceive);
            m_TcpClient.OnClose          += new TcpClientEvent.OnCloseEventHandler(OnClose);

            m_Queue.Clear();
            m_TempQueue.Clear();
            this.m_sIP   = sIP;
            this.m_nPort = (ushort)nPort;
            return(this.Connect(true));
        }
Ejemplo n.º 8
0
 private HandleResult OnClose(HPSocketCS.TcpClient sender)
 {
     this.Dispose();
     return(HandleResult.Ok);
 }
Ejemplo n.º 9
0
 private HandleResult _client_OnConnect(TcpClient sender)
 {
     //Send("Hello we connected,呵呵");
     _log.Debug("Server connected ");
     return HandleResult.Ok;
 }
Ejemplo n.º 10
0
 private HandleResult OnConnect(HPSocketCS.TcpClient sender)
 {
     sender.GetListenAddress(ref _remoteIP, ref _port);
     return(HandleResult.Ok);
 }
Ejemplo n.º 11
0
 private HandleResult _client_OnPrepareConnect(TcpClient sender, uint socket)
 {
     _log.Debug("Ready to connect...... ");
     return HandleResult.Ok;
 }
Ejemplo n.º 12
0
 private HandleResult _client_OnError(TcpClient sender, SocketOperation enOperation, int errorCode)
 {
     return HandleResult.Ok;
 }
Ejemplo n.º 13
0
        HandleResult OnSend(TcpClient sender, IntPtr pData, int length)
        {
            // 客户端发数据了
            AddMsg(string.Format(" > [{0},OnSend] -> ({1} bytes)", sender.ConnectionId, length));

            return HandleResult.Ok;
        }
Ejemplo n.º 14
0
 HandleResult OnSend(TcpClient sender, IntPtr pData, int length)
 {
     // 客户端发数据了
     Interlocked.Add(ref TotalSent, length);
     return HandleResult.Ok;
 }
Ejemplo n.º 15
0
 private HandleResult _client_OnReceive(TcpClient sender, IntPtr pData, int length)
 {
     try
     {
         Receive(sender, pData, length);
     }
     catch (Exception ex)
     {
         _log.Error("Client receive exception", ex);
         return HandleResult.Ignore;
     }
     return HandleResult.Ok;
 }
Ejemplo n.º 16
0
 private HandleResult _client_OnClose(TcpClient sender)
 {
     Stop();
     _log.Debug("Disconnecting from the server ");
     return HandleResult.Ok;
 }
Ejemplo n.º 17
0
 private HandleResult _client_OnSend(TcpClient sender, IntPtr pData, int length)
 {
     byte[] bytes = new byte[length];
     Marshal.Copy(pData, bytes, 0, length);
     String message = Encoding.Unicode.GetString(bytes);
     return HandleResult.Ok;
 }
Ejemplo n.º 18
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                string address = this.txtIpAddress.Text.Trim();
                ushort port = ushort.Parse(this.txtPort.Text.Trim());
                TestTimes = int.Parse(this.cbxTestTime.Text.Trim());
                TestInterv = int.Parse(this.cbxTestInterv.Text.Trim());
                ThreadCount = int.Parse(this.cbxThreadCount.Text.Trim());
                ThreadInterv = int.Parse(this.cbxThreadInterv.Text.Trim());
                DataLength = int.Parse(this.cbxDataLength.Text.Trim());
                if (CheckParams() == false)
                {
                    throw new Exception("params error!");
                }

                SetAppState(AppState.Starting);

                Timeconsuming = 0;
                TotalReceived = 0;
                TotalSent = 0;
                ExpectReceived = (Int64)TestTimes * (Int64)ThreadCount * (Int64)DataLength;

                clientList.Clear();

                // 创建指定线程个数的客户端
                for (int i = 0; i < ThreadCount; i++)
                {
                    TcpClient client = new TcpClient();
                    client.SetCallback(OnPrepareConnect, OnConnect, OnSend, OnReceive, OnClose, OnError);
                    if (client.Start(address, port) == true)
                    {
                        clientList.Add(client);
                    }
                    else
                    {
                        foreach (var c in clientList)
                        {
                            c.Stop();
                        }
                        clientList.Clear();
                        throw new Exception(string.Format(" > {2}, Connection to server fail ->({0},{1})", client.GetlastError(), client.GetLastErrorDesc(), i));
                    }
                }

                AddMsg(string.Format("$ Client start ok -> ({0}:{1})", address, port));

                // 延迟3秒
                int sendDelay = 3;
                AddMsg(string.Format(" *** willing to send data after {0} seconds ...", sendDelay));
                // Delay2(sendDelay * 1000);

                SetAppState(AppState.Started);

                testThread = new Thread(delegate()
                {
                    Thread.Sleep(sendDelay * 1000);
                    AddMsg(string.Format(" *** begin... ***", sendDelay));
                    // 发送的数据包
                    byte[] sendBytes = new byte[DataLength];

                    StopWatch.Restart();
                    bool isTerminated = false;
                    for (int i = 0; i < TestTimes; i++)
                    {
                        for (int j = 0; j < ThreadCount; j++)
                        {
                            TcpClient client = clientList[j];
                            if (client.Send(sendBytes, sendBytes.Length) == false)
                            {
                                AddMsg(string.Format("$ Client send fail [sock: {0}, seq: {1}] -> {3} ({2})",
                                                     i + 1,
                                                     j + 1,
                                                     client.SYSGetLastError(),
                                                     client.GetSocketErrorDesc(SocketError.DataSend)));
                                isTerminated = true;
                                break;
                            }

                            if (ThreadInterv > 0 && j + 1 < ThreadCount)
                            {
                                Thread.Sleep(ThreadInterv);
                                //Delay2(ThreadInterv);
                            }
                        }

                        if (isTerminated == true)
                        {
                            break;
                        }

                        if (TestInterv > 0 && i + 1 < TestTimes)
                        {
                            Thread.Sleep(TestInterv);
                            //Delay2(TestInterv);
                        }
                    }
                });
                testThread.Start();
            }
            catch (Exception ex)
            {
                SetAppState(AppState.Stoped);
                AddMsg(string.Format("$ Start fail msg:{0}", ex.Message));
            }
        }
Ejemplo n.º 19
0
 HandleResult OnError(TcpClient sender, SocketOperation enOperation, int errorCode)
 {
     // 出错了
     return HandleResult.Ok;
 }
Ejemplo n.º 20
0
 HandleResult OnClose(TcpClient sender)
 {
     // 连接关闭了
     return HandleResult.Ok;
 }
Ejemplo n.º 21
0
        HandleResult OnReceive(TcpClient sender, IntPtr pData, int length)
        {
            // 数据到达了

            Interlocked.Add(ref TotalReceived, length);
            if (TotalReceived == ExpectReceived)
            {
                StopWatch.Stop();
                Timeconsuming = StopWatch.ElapsedMilliseconds;
                AddMsg(string.Format("Total time consuming: {0}", Timeconsuming));
            }

            return HandleResult.Ok;
        }
Ejemplo n.º 22
0
 private HandleResult OnError(HPSocketCS.TcpClient sender, SocketOperation enOperation, int errorCode)
 {
     this.Dispose();
     return(HandleResult.Ok);
 }
Ejemplo n.º 23
0
        HandleResult OnReceive(TcpClient sender, byte[] bytes)
        {
            // 数据到达了

            AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", sender.ConnectionId, bytes.Length));

            return HandleResult.Ok;
        }
Ejemplo n.º 24
0
 HandleResult OnPrepareConnect(TcpClient sender, uint socket)
 {
     return HandleResult.Ok;
 }
Ejemplo n.º 25
0
        HandleResult OnSend(TcpClient sender, byte[] bytes)
        {
            // 客户端发数据了
            AddMsg(string.Format(" > [{0},OnSend] -> ({1} bytes)", sender.ConnectionId, bytes.Length));

            return HandleResult.Ok;
        }
Ejemplo n.º 26
0
        HandleResult OnReceive(TcpClient sender, IntPtr pData, int length)
        {
            // 数据到达了
            if (isSendFile == true)
            {
                // 如果发送了文件,并接收到了返回数据
                isSendFile = false;
                MyFileInfo myFile = (MyFileInfo)Marshal.PtrToStructure(pData, typeof(MyFileInfo));
                int objSize = Marshal.SizeOf(myFile);
                // 因为没有附加尾数据,所以大小可以用length - objSize
                byte[] bytes = new byte[length - objSize];
                Marshal.Copy(pData + objSize, bytes, 0, length - objSize);

                string txt = Encoding.Default.GetString(bytes);
                string msg = string.Empty;
                if (txt.Length > 100)
                {
                    msg = txt.Substring(0, 100) + "......";
                }
                else
                {
                    msg = txt;
                }

                AddMsg(string.Format(" > [{0},OnReceive] -> FileInfo(Path:\"{1}\",Size:{2})", sender.ConnectionId, myFile.FilePath, myFile.FileSize));
                AddMsg(string.Format(" > [{0},OnReceive] -> FileContent(\"{1}\")", sender.ConnectionId, msg));
            }
            else if (studentType != StudentType.None)
            {
                byte[] bytes = new byte[length];
                Marshal.Copy(pData, bytes, 0, length);

                switch (studentType)
                {
                    case StudentType.Array:
                        Student[] students = sender.BytesToObject(bytes) as Student[];
                        foreach (var stu in students)
                        {
                            AddMsg(string.Format(" > [{0},OnReceive] -> Student({1},{2},{3})", sender.ConnectionId, stu.Id, stu.Name, stu.GetSexString()));
                        }
                        break;
                    case StudentType.List:
                        List<Student> stuList = sender.BytesToObject(bytes) as List<Student>;
                        foreach (var stu in stuList)
                        {
                            AddMsg(string.Format(" > [{0},OnReceive] -> Student({1},{2},{3})", sender.ConnectionId, stu.Id, stu.Name, stu.GetSexString()));
                        }
                        break;
                    case StudentType.Single:
                        Student student = sender.BytesToObject(bytes) as Student;
                        AddMsg(string.Format(" > [{0},OnReceive] -> Student({1},{2},{3})", sender.ConnectionId, student.Id, student.Name, student.GetSexString()));
                        studentType = StudentType.None;
                        break;
                }
            }
            else
            {
                AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", sender.ConnectionId, length));
            }

            return HandleResult.Ok;
        }
Ejemplo n.º 27
0
 HandleResult OnConnect(TcpClient sender)
 {
     // 已连接 到达一次
     AddMsg(string.Format(" > [{0}, OnConnect]", sender.ConnectionId));
     return HandleResult.Ok;
 }
Ejemplo n.º 28
0
        HandleResult OnHandShake(TcpClient client)
        {
            // ssl握手了
            AddMsg(string.Format(" > [{0},OnHandShake])", client.ConnectionId));

            return HandleResult.Ok;
        }
Ejemplo n.º 29
0
 private void Receive(TcpClient sender, IntPtr pData, int length)
 {
     byte[] bytes = new byte[length];
     Marshal.Copy(pData, bytes, 0, length);
     String message = Encoding.Unicode.GetString(bytes);
     //String message = sender.ByteToStructure<String>(bytes);
     AddMessageInvoke(String.Format("->{0}", message));
 }
Ejemplo n.º 30
-1
        static HandleResult OnConnect(TcpClient sender)
        {
            // 已连接 到达一次

            // 如果是异步联接,更新界面状态
            //this.Invoke(new ConnectUpdateUiDelegate(ConnectUpdateUi));

            AddMsg(string.Format(" > [{0},OnConnect]", sender.ConnectionId));

            return HandleResult.Ok;
        }