Server side example
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

using NTCPMSG.Server;
using NTCPMSG.Event;

namespace Example
{
    class Server
    {
        /// <summary>
        /// DataReceived event will be called back when server get message from client which connect to.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        static void ReceiveEventHandler(object sender, ReceiveEventArgs args)
        {
            switch ((Event)args.Event)
            {
                case Event.OneWay:
                    //Get OneWay message from client
                    if (args.Data != null)
                    {
                        try
                        {
                            if (args.CableId != 0)
                            {
                                Console.WriteLine("Get one way message from cable {0}", args.CableId);
                            }
                            else
                            {
                                Console.WriteLine("Get one way message from {0}", args.RemoteIPEndPoint);
                            }

                            Console.WriteLine(Encoding.UTF8.GetString(args.Data));
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                    break;
                case Event.Return:
                    //Get return message from client
                    if (args.Data != null)
                    {
                        try
                        {
                            int fromClient = BitConverter.ToInt32(args.Data, 0);

                            args.ReturnData = BitConverter.GetBytes(++fromClient);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                    break;
            }
        }

        /// <summary>
        /// RemoteDisconnected event will be called back when specified client disconnected.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        static void DisconnectEventHandler(object sender, DisconnectEventArgs args)
        {
            Console.WriteLine("Remote socket:{0} disconnected.", args.RemoteIPEndPoint);
        }

        /// <summary>
        /// Accepted event will be called back when specified client connected
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        static void AcceptedEventHandler(object sender, AcceptEventArgs args)
        {
            Console.WriteLine("Remote socket:{0} connected.", args.RemoteIPEndPoint);
        }

        public static void Run(string[] args)
        {
            NTCPMSG.Server.NTcpListener listener;

            //Create a tcp listener that listen 2500 TCP port.
            listener = new NTcpListener(new IPEndPoint(IPAddress.Any, 2500));

            //DataReceived event will be called back when server get message from client which connect to.
            listener.DataReceived += new EventHandler<ReceiveEventArgs>(ReceiveEventHandler);

            //RemoteDisconnected event will be called back when specified client disconnected.
            listener.RemoteDisconnected += new EventHandler<DisconnectEventArgs>(DisconnectEventHandler);

            //Accepted event will be called back when specified client connected
            listener.Accepted += new EventHandler<AcceptEventArgs>(AcceptedEventHandler);

            //Start listening.
            //This function will not block current thread.
            listener.Listen();

            Console.WriteLine("Listening...");

            while (true)
            {
                System.Threading.Thread.Sleep(5 * 1000);

                //Push message to client example.
                foreach (IPEndPoint clientIpEndPoint in listener.GetRemoteEndPoints())
                {
                    bool successful = listener.AsyncSend(clientIpEndPoint, (uint)Event.PushMessage,
                        Encoding.UTF8.GetBytes("I am from server!"));

                    if (successful)
                    {
                        Console.WriteLine(string.Format("Push message to {0} successful!",
                            clientIpEndPoint));
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Push message to {0} fail!",
                            clientIpEndPoint));
                    }
                }

                foreach (UInt16 cableId in listener.GetCableIds())
                {
                    bool successful = listener.AsyncSend(cableId, (uint)Event.PushMessage,
                        Encoding.UTF8.GetBytes(string.Format("Hi cable {0}!", cableId)));

                    if (successful)
                    {
                        Console.WriteLine(string.Format("Push message to cable {0} successful!",
                            cableId));
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Push message to cable {0} fail!",
                            cableId));
                    }
                }
            }

            //System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
        }
    }
}

Client side example

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

using NTCPMSG.Client;
using NTCPMSG.Event;

namespace Example
{
    class Client
    {
        /// <summary>
        /// DataReceived event will be called back when server get message from client which connect to.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        static void ReceiveEventHandler(object sender, ReceiveEventArgs args)
        {
            switch ((Event)args.Event)
            {
                case Event.PushMessage:
                    //Get OneWay message from server
                    if (args.Data != null)
                    {
                        try
                        {
                            Console.WriteLine(Encoding.UTF8.GetString(args.Data));
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                    break;
            }

        }

        public static void Run(string[] args)
        {
            Console.Write("Please input server IP Address [127.0.0.1]:");
            string ipAddress = Console.ReadLine().Trim().ToLower();

            if (ipAddress == "")
            {
                ipAddress = "127.0.0.1";
            }

            try
            {
                //************** SingConnection Example **********************

                Console.Write("Press any key to start single connection example");
                Console.ReadKey();
                Console.WriteLine();

                //Create a SingleConnection instanace that will try to connect to host specified in 
                //ipAddress and port (2500).
                SingleConnection client =
                    new SingleConnection(new IPEndPoint(IPAddress.Parse(ipAddress), 2500));
                client.ReceiveEventHandler += new EventHandler<ReceiveEventArgs>(ReceiveEventHandler);

                client.Connect();

                Console.WriteLine("AsyncSend: Hello world! I am Single");

                //Send an asynchronously message to server
                client.AsyncSend((UInt32)Event.OneWay, Encoding.UTF8.GetBytes("Hello world! I am Single"));

                int number = 0;

                try
                {
                    Console.WriteLine("SyncSend {0}", number);

                    //send a synchronously message to server
                    //send a number with event: Event.Return to server and get the response from server 
                    //with the number increased.
                    byte[] retData = client.SyncSend((UInt32)Event.Return, BitConverter.GetBytes(number));

                    number = BitConverter.ToInt32(retData, 0);

                    Console.WriteLine("Get {0}", number);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                Console.WriteLine("Waitting for 10 seconds to finish simple connection example.");
                System.Threading.Thread.Sleep(10000);

                client.Close();

                //************* SingleConnectionCable Example *****************
                Console.Write("Press any key to start single connection cable example");
                Console.ReadKey();
                Console.WriteLine();

                //Create a SingleConnectionCable instance that will try to connect to host specified in 
                //ipAddress and port (2500).
                //by default, SingleConnectionCable will try to connect automatically and including 6 tcp connections.
                SingleConnectionCable clientCable =
                    new SingleConnectionCable(new IPEndPoint(IPAddress.Parse(ipAddress), 2500));
                
                clientCable.ReceiveEventHandler += new EventHandler<ReceiveEventArgs>(ReceiveEventHandler);
                clientCable.Connect();

                Console.WriteLine("AsyncSend: Hello world! I am Cable {0}", clientCable.CableId);
                //Send a one way message to server
                clientCable.AsyncSend((UInt32)Event.OneWay, Encoding.UTF8.GetBytes(string.Format("Hello world! I am Cable {0}", clientCable.CableId)));

                while (true)
                {
                    Console.WriteLine("SyncSend {0}", number);

                    try
                    {
                        //send a number with event: Event.Return to server and get the response from server 
                        //with the number increased.
                        byte[] retData = clientCable.SyncSend((UInt32)Event.Return, BitConverter.GetBytes(number));

                        number = BitConverter.ToInt32(retData, 0);

                        Console.WriteLine("Get {0}", number);

                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    Console.WriteLine("Quit when you press ESC. Else continue SyncSend.");

                    //Quit when you press ESC
                    if (Console.ReadKey().KeyChar == 0x1B)
                    {
                        clientCable.Close();
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.ReadLine();
            }
        }
    


    }
}


Event.cs

    public enum Event
    {
        OneWay = 1,

        Return = 2,

        PushMessage = 3,
    }

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

using NTCPMSG.Server;
using NTCPMSG.Event;

namespace Example
{
    class Server
    {
        /// <summary>
        /// DataReceived event will be called back when server get message from client which connect to.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        static void ReceiveEventHandler(object sender, ReceiveEventArgs args)
        {
            switch ((Event)args.Event)
            {
                case Event.OneWay:
                    //Get OneWay message from client
                    if (args.Data != null)
                    {
                        try
                        {
                            if (args.CableId != 0)
                            {
                                Console.WriteLine("Get one way message from cable {0}", args.CableId);
                            }
                            else
                            {
                                Console.WriteLine("Get one way message from {0}", args.RemoteIPEndPoint);
                            }

                            Console.WriteLine(Encoding.UTF8.GetString(args.Data));
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                    break;
                case Event.Return:
                    //Get return message from client
                    if (args.Data != null)
                    {
                        try
                        {
                            int fromClient = BitConverter.ToInt32(args.Data, 0);

                            args.ReturnData = BitConverter.GetBytes(++fromClient);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                    break;
            }
        }

        /// <summary>
        /// RemoteDisconnected event will be called back when specified client disconnected.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        static void DisconnectEventHandler(object sender, DisconnectEventArgs args)
        {
            Console.WriteLine("Remote socket:{0} disconnected.", args.RemoteIPEndPoint);
        }

        /// <summary>
        /// Accepted event will be called back when specified client connected
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        static void AcceptedEventHandler(object sender, AcceptEventArgs args)
        {
            Console.WriteLine("Remote socket:{0} connected.", args.RemoteIPEndPoint);
        }

        public static void Run(string[] args)
        {
            NTCPMSG.Server.NTcpListener listener;

            //Create a tcp listener that listen 2500 TCP port.
            listener = new NTcpListener(new IPEndPoint(IPAddress.Any, 2500));

            //DataReceived event will be called back when server get message from client which connect to.
            listener.DataReceived += new EventHandler<ReceiveEventArgs>(ReceiveEventHandler);

            //RemoteDisconnected event will be called back when specified client disconnected.
            listener.RemoteDisconnected += new EventHandler<DisconnectEventArgs>(DisconnectEventHandler);

            //Accepted event will be called back when specified client connected
            listener.Accepted += new EventHandler<AcceptEventArgs>(AcceptedEventHandler);

            //Start listening.
            //This function will not block current thread.
            listener.Listen();

            Console.WriteLine("Listening...");

            while (true)
            {
                System.Threading.Thread.Sleep(5 * 1000);

                //Push message to client example.
                foreach (IPEndPoint clientIpEndPoint in listener.GetRemoteEndPoints())
                {
                    bool successful = listener.AsyncSend(clientIpEndPoint, (uint)Event.PushMessage,
                        Encoding.UTF8.GetBytes("I am from server!"));

                    if (successful)
                    {
                        Console.WriteLine(string.Format("Push message to {0} successful!",
                            clientIpEndPoint));
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Push message to {0} fail!",
                            clientIpEndPoint));
                    }
                }

                foreach (UInt16 cableId in listener.GetCableIds())
                {
                    bool successful = listener.AsyncSend(cableId, (uint)Event.PushMessage,
                        Encoding.UTF8.GetBytes(string.Format("Hi cable {0}!", cableId)));

                    if (successful)
                    {
                        Console.WriteLine(string.Format("Push message to cable {0} successful!",
                            cableId));
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Push message to cable {0} fail!",
                            cableId));
                    }
                }
            }

            //System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
        }
    }
}

Last edited Oct 3, 2012 at 4:11 AM by eaglet2006, version 3

Comments

No comments yet.