none
client端如何使用Socket非同步接收資料? RRS feed

  • 問題

  • 我在Socket 的Server端已經寫好一支程式,由client端下一個指令送給Server,Server就會每隔1秒會丟出訊號(return value),我參考http://msdn2.microsoft.com/en-us/library/bbx2eya8(vs.71).aspx 文章裡面的寫法:

     

    private static void Receive(Socket client) {
        try {
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.
            client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
       }

     

    private static void ReceiveCallback( IAsyncResult ar ) {
        try {
            // Retrieve the state object and the client socket
            // from the asynchronous state object.
            StateObject state = (StateObject) ar.AsyncState;
            Socket client = state.workSocket;
            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);
            if (bytesRead > 0) {
                // There might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
                    //  Get the rest of the data.
                client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
                    new AsyncCallback(ReceiveCallback), state);
            } else {
                // All the data has arrived; put it in response.
                if (state.sb.Length > 1) {
                    response = state.sb.ToString();
                }
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }

    這是一個WindowApplication但卻不知道該何時呼叫Receive(skt),放在Form_Load也不對,必須等我下命令(btnSend_click),可是在btnSend_click事件程序中呼叫Receive也不對,因為以後的Receive是每隔1秒自動接收ㄉ!

     

    我若使用AxWinsock 6.0 的Activex Control裡面有一個Data_Arrival的事件,我的問題就可迎刃而解,但是使用.NET 的Socket 反而不知道該如何接收回傳值?

     

    請問有誰可以教教我呢,先感謝嚕

    2007年7月4日 上午 01:31