quinta-feira, 30 de julho de 2015

Notification Server C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Net.Sockets;
using System.Timers;
using PushNotificationService.Monitoring;
using System.Threading;
using PushNotificationService.Settings;

namespace PushNotificationService
{
    public partial class UpdateTableService : ServiceBase
    {
        public UpdateTableService()
        {
            InitializeComponent();
            ServiceSettings.activeInstance().setXmlPath(@"PushNotificationService\");

            PendingMessages pm = new PendingMessages();

            Thread t_processPendingMessages = new Thread(new ThreadStart(pm.process));
            t_processPendingMessages.Start();
        }

        protected override void OnStart(string[] args)
        {
            TcpListener serverSocket = new TcpListener(8888);
            TcpClient clientSocket = default(TcpClient);
            int counter = 0;


            //inicia o servidor
            serverSocket.Start();
            Console.WriteLine(" >> " + "Server Started");

            counter = 0;
            while (true)
            {
                //espera e aceita requisição do cliente
                clientSocket = serverSocket.AcceptTcpClient();
                Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
                HandleClient client = new HandleClient();
                client.startClient(clientSocket);
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine(" >> " + "exit");
            Console.ReadLine();
        }

        protected override void OnStop()
        {

        }

        ///
        /// Método chamado para inciar o serviço
        ///
        ///
        /// Argumentos opcionais para iniciar o serviço
        ///
        public void Start(string[] args)
        {
            this.OnStart(args);
        }
    }
}


using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;

namespace PushNotificationService
{
    //Class to handle each client request separatly
    public class HandleClient
    {
        TcpClient clientSocket;
        Dictionary<String, TcpClient> hashT = PhoneHash.Instance.Table;

        ///

        ///     inicia a troca de mensagens entre cliente e servidor
        ///

        ///
        public void startClient(TcpClient inClientSocket)
        {
            this.clientSocket = inClientSocket;
            Thread ctThread = new Thread(doChat);
            ctThread.Start();
        }

        ///

        ///     troca mensagens entre cliente e servidor
        ///

        private void doChat()
        {
            int requestCount = 0;
            byte[] bytesFrom = new byte[10025];
            string dataFromClient = null;
           
            string rCount = null;
            requestCount = 0;

          

                try
                {
                    //lê os dados transmitidos pelo cliente
                    requestCount = requestCount + 1;
                    NetworkStream networkStream = clientSocket.GetStream();
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);

                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);

                    if (dataFromClient.Contains('$'))
                    {
                        //parseia o dado enviado com caractere '$' no final

                        int indexTel = dataFromClient.IndexOf("$");
                        String phoneNum = dataFromClient.Substring(0, indexTel);
                        storeData(phoneNum, clientSocket);


                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(" >> " + ex.ToString());
                }
           
        }


        private bool storeData(String phoneId, TcpClient clientSocket)
        {
            try
            {
                if (hashT.ContainsKey(phoneId))
                {
                    hashT[phoneId] = clientSocket;
                    return true;
                }
                else
                {
                    hashT.Add(phoneId, clientSocket);
                    return true;
                }
            }
            catch {
                return false;
            }
        }

        public void sendMessage(String phoneId)
        {
            Byte[] sendBytes = null;
            string serverResponse = null;
            TcpClient socketSaved = null;


            if (hashT.ContainsKey(phoneId))
            {
                socketSaved = hashT[phoneId];

                NetworkStream networkStream = socketSaved.GetStream();

                //envio de mensagem
                serverResponse = "Nova mensagem para " + phoneId;

                sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                networkStream.Write(sendBytes, 0, sendBytes.Length);
                networkStream.Flush();
            }
        }

        private Exception formatException(String method, Exception ex)
        {
            return new Exception("PushNotification : HandleClient | Method: " + method + "", ex);
        }
    }
}

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


public class PhoneHash
{
    private static PhoneHash instance;
    private Dictionary<String, TcpClient> table;

    private PhoneHash() {
        table = new Dictionary<String, TcpClient>();
    }

    public static PhoneHash Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new PhoneHash();
            }
            return instance;
        }
    }

    public Dictionary<String, TcpClient> Table
    {
        get { return table; }
        set { table = value; }
    }

}
Postar um comentário