www.pudn.com > windows_mobile_5.0_socket.rar > DeviceSocket.cs


using System; 
using System.Collections.Generic; 
using System.Text; 
 
using System.Net; 
using System.Net.Sockets; 
using System.Threading; 
 
 
namespace CS_CATClient 
{ 
    ///  
    /// Socket notification events. 
    ///  
    public enum NotifyEvents 
    { 
        Connected, 
        DataSent, 
        DataReceived, 
        Disconnected, 
        ConnectError, 
        SendError, 
        ReceiveError, 
        DisconnectError, 
        OtherError 
    } 
 
    // Socket communications will be done asynchronously 
    public class DeviceSocket 
    { 
        // The Socket class provides a rich set of methods and properties for network communications via sockets.  
        // Although Socket class supports both synchronous and asynchronous data transfers, we choose asynchronous  
        // method here 
        public Socket mySocket = null; 
 
        // Used to synchronize the shutdown process, terminate 
        // any pending async calls before Disconnect returns 
        ManualResetEvent asyncEvent = new ManualResetEvent(true); 
 
        // private string terminator = ""; 
 
        public string receiveBuf = null; 
        private const int BUFFER_SIZE = 1024; 
 
        // notification event 
        public delegate void NotifyEventHandler(NotifyEvents nEvent, object data); 
        public event NotifyEventHandler Notify; 
 
        // Closing flag 
        private bool closing = false; 
        byte[] bRcvd = new byte[BUFFER_SIZE]; 
 
        ///  
        /// Connect to the specified address and port number. 
        ///  
        public void Connect(String ip, int port) 
        { 
            // Create a socket object 
            // The addressFamily parameter (Address for IP version 4) specifies the addressing scheme the Socket class  
            // The socketType parameter specifies the type of the Socket class 
            // The protocolType parameter (tcp - Transmission Control Protocol) specifies the protocol used by Socket 
            mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
 
            // Sets the state of the event to nonsignaled, causing threads to block 
            asyncEvent.Reset(); 
 
            // Prepare for async connection 
            IPAddress ipAddress = IPAddress.Parse(ip); 
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port); 
 
            // Begins an asynchronous request for a remote host connection 
            mySocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null); 
 
            // wait for any async operations to complete 
            asyncEvent.WaitOne(); 
        } 
 
        ///  
        /// The property Socket.Connected does not always indicate if the socket is currently  
        /// connected, this polls the socket to determine the latest connection state. 
        ///  
        /// Returns True or False 
        ///  
        public bool IsConnected 
        { 
            get 
            { 
                if (mySocket == null)   return false; 
 
                // the socket is not connected if the Connected property is false 
                if (!mySocket.Connected)    return false; 
 
                // there is no guarantee that the socket is connected even if the 
                // Connected property is true 
                try 
                { 
                    // poll for error to see if socket is connected 
                    return !mySocket.Poll(1, SelectMode.SelectError); 
                } 
                catch 
                { 
                    return false; 
                } 
            } 
        } 
 
        ///  
        /// Async connect callback 
        ///  
        private void OnConnect(IAsyncResult ar) 
        { 
            try 
            { 
                // Ends a pending asynchronous connection request 
                mySocket.EndConnect(ar); 
 
                // Assert: Connected. Notify the app. 
                NotifyCaller(NotifyEvents.Connected, null); 
            } 
            catch (Exception ex) 
            { 
                NotifyCaller(NotifyEvents.ConnectError, ex.Message); 
            } 
        } 
 
        ///  
        /// Disconnect a connected socket 
        ///  
        public void Disconnect() 
        { 
            // if the socket is not created 
            if (mySocket == null) return; 
 
            closing = true; 
 
            try 
            { 
                // first, shutdown the socket 
                mySocket.Shutdown(SocketShutdown.Both); 
            } 
            catch { } 
 
            try 
            { 
                // next, close the socket which terminates any pending 
                // async operations 
                mySocket.Close(); 
 
                // wait for any async operations to complete 
                asyncEvent.WaitOne(); 
            } 
            catch { } 
 
            closing = false; 
 
        } 
 
		///  
		/// Send data to the server. 
		///  
        public void Send(String data) 
        { 
            try 
            { 
                // String must be converted to byet[] 
                byte[] byteArray = new ASCIIEncoding().GetBytes(data); 
 
                // Send the data to the connected socket 
                // mySocket.BeginSend(byteArray, 0, byteArray.Length, SocketFlags.None, null, null); 
                mySocket.BeginSend(byteArray, 0, byteArray.Length, SocketFlags.None, new AsyncCallback(OnSend), null); 
 
                asyncEvent.Reset(); 
 
                // Send the terminator 
                // mySocket.BeginSend(new ASCIIEncoding().GetBytes(terminator), 0, terminator.Length, SocketFlags.None, new AsyncCallback(OnSend), true); 
            } 
            catch (Exception ex) 
            { 
                NotifyCaller(NotifyEvents.SendError, ex.Message); 
            } 
 
        } 
 
        ///  
        /// Async send callback 
        ///  
        private void OnSend(IAsyncResult ar) 
        { 
            try 
            { 
                mySocket.EndSend(ar); 
 
                // ASSERT: Data sent successfully 
                NotifyCaller(NotifyEvents.DataSent, null); 
            } 
            catch (Exception ex) 
            { 
                NotifyCaller(NotifyEvents.SendError, ex.Message); 
            } 
        } 
 
		///  
		/// Receive data from the server. 
		///  
        public void Receive() 
        { 
            try 
            { 
                asyncEvent.Reset(); 
 
                mySocket.BeginReceive(bRcvd, 0, BUFFER_SIZE, SocketFlags.None, new AsyncCallback(OnReceive), null); 
 
                //Thread.Sleep(1000); 
            } 
            catch (Exception ex) 
            { 
                NotifyCaller(NotifyEvents.ReceiveError, ex.Message); 
            } 
        } 
 
        ///  
        /// Async send callback 
        ///  
        private void OnReceive(IAsyncResult ar) 
        { 
            try 
            { 
                int len = mySocket.EndReceive(ar); 
                receiveBuf = ASCIIEncoding.ASCII.GetString(bRcvd, 0, len); 
 
                // ASSERT: Data receieved successfully 
                NotifyCaller(NotifyEvents.DataReceived, receiveBuf); 
            } 
            catch (Exception ex) 
            { 
                NotifyCaller(NotifyEvents.ReceiveError, ex.Message); 
            } 
        } 
 
        ///  
        /// Notify the app 
        ///  
        private void NotifyCaller(NotifyEvents nEvent, object data) 
        { 
            // the async operation has completed 
            asyncEvent.Set(); 
 
            // don't raise notification events when disconnecting 
            if ((this.Notify != null) && !closing) 
                Notify(nEvent, data); 
        } 
 
    } 
}