Пример #1
0
        private void TcpServerReceiveCallback(IAsyncResult ar)
        {
            StateObject user = new StateObject();

            user = (StateObject)ar.AsyncState;
            Socket tmpSocket = user.workSocket;

            // 從客戶端讀取資料
            int bytesRead = user.workSocket.EndReceive(ar);

            if (bytesRead > 0) // 有資料
            {
                // 客戶端資料
                String MSG = Encoding.ASCII.GetString(user.buffer).Trim("\0".ToCharArray());
                txtTcpRece.Invoke(updateTxt, MSG, txtTcpRece);
                if (Islog)
                {
                    NLogHelp.WriteLog("--" + MSG, tmpSocket.LocalEndPoint.ToString());
                }
            }
            // 清除舊資料
            user.buffer = new byte[user.BufferSize];
            // 等待客戶端再次傳送資料
            user.workSocket.BeginReceive(user.buffer, 0, user.BufferSize, 0, new AsyncCallback(ReceiveCallback), user);
        }
Пример #2
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                StateObject state = null;
                state = (StateObject)ar.AsyncState;
                Socket server = state.workSocket;
                //!tmpSocket.Poll(10, SelectMode.SelectRead)


                if (state.workSocket.Connected)
                {
                    // 從主機端讀取資料
                    int bytesRead = server.EndReceive(ar);
                    // 有資料
                    if (bytesRead > 0)
                    {
                        String MSG = Encoding.ASCII.GetString(state.buffer).Trim("\0".ToCharArray());
                        if (txtTcpRece.InvokeRequired)
                        {
                            txtTcpRece.BeginInvoke(updateTxt, MSG, txtTcpRece);
                        }
                        else
                        {
                            txtTcpRece.AppendText(MSG + Environment.NewLine);
                        }
                        if (Islog)
                        {
                            NLogHelp.WriteLog("--" + MSG, server.LocalEndPoint.ToString());
                        }
                    }

                    // 繼續等待主機回傳的資料
                    state.buffer = new byte[state.BufferSize];

                    state.workSocket.BeginReceive(state.buffer, 0, state.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                }
                else
                {
                    txtTcpRece.BeginInvoke(updateTxt, Environment.NewLine + state.workSocket.LocalEndPoint.ToString() + "连接断开", txtTcpRece);

                    ClientLists.Remove(state);
                    listBoxClient.Invoke(updateListBox, state.workSocket, listBoxClient);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }