C#套接字服务器发送给列表中的所有客户端

时间:2016-08-10 13:23:20

标签: c# sockets

我想让我的套接字列表上的所有客户从服务器接收消息,并在收到这样的消息后同时发送,但我不能。我需要使用Lamport时钟理论在客户端之间进行时钟同步。

服务器:

namespace TCPSocketServer
{
    class Server
    {
        private Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        private List<Socket> ListaDeClientesSockets = new List<Socket>();   /*Lista de sockets para adicionar clientes*/
        private const int _BUFFER_SIZE = 2048;
        private int _PORT;
        private string Ip;
        private byte[] _buffer = new byte[_BUFFER_SIZE];

        public Server(string IP, int port)  /*Construtor para inicialização do IP e da Porta*/
        {
            this.Ip = IP;
            this._PORT = port;
        }

        public  void Connect()
        {
            Console.WriteLine("Servidor Socket ON");
            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, _PORT));
            _serverSocket.Listen(5);
            _serverSocket.BeginAccept(AcceptCallback, null);
        }


        private void Send()
        {
            foreach(Socket socket in ListaDeClientesSockets)
            {
                byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());
                socket.Send(data);
                Console.WriteLine("Horas enviada do cliente");
            }
        }

        private  void FecharConexaoSocket()
        {
            foreach (Socket socket in ListaDeClientesSockets)
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }

            _serverSocket.Close();
        }

        /// <summary>AcceptCallback método da classe Server
        /// Evento realizado para aceitar conexões dos clientes adicionando em uma lista genérica
        /// /// </summary>

        private void AcceptCallback(IAsyncResult asyncronousResult)
        {
            Socket socket;

            try
            {
                socket = _serverSocket.EndAccept(asyncronousResult);
            }
            catch (ObjectDisposedException)
            {
                return;
            }

            ListaDeClientesSockets.Add(socket);
            socket.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
            Console.WriteLine("Cliente Conectado " + socket.RemoteEndPoint.ToString());
            _serverSocket.BeginAccept(AcceptCallback, null);
        }

        /// <summary>ReceiveCallBack método da classe Server
        /// Evento realizado para receber e enviar dados do cliente através de um IASyncResult
        /// </summary>

        private  void ReceiveCallback(IAsyncResult asyncronousResult)   
        {
            Socket current = (Socket)asyncronousResult.AsyncState;
            int received;

            try
            {
                received = current.EndReceive(asyncronousResult);
            }
            catch (SocketException) /*Catch realizado caso houver perca de conexão com o cliente*/
            {
                Console.WriteLine("Conexão com o cliente " + current.RemoteEndPoint.ToString() + " perdida.");
                current.Close();
                ListaDeClientesSockets.Remove(current);
                return;
            }

            byte[] recBuf = new byte[received];
            Array.Copy(_buffer, recBuf, received);
            string text = Encoding.ASCII.GetString(recBuf);
            Console.WriteLine("Texto recebido: " + text);

            if (text == "horas")
            {
                /*byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());
                current.Send(data);*/
                Send();
                //Console.WriteLine("Horas enviada do cliente");
                Console.WriteLine(ListaDeClientesSockets.Count);
            }
            else if (text == "desconectar")
            {
                current.Shutdown(SocketShutdown.Both);
                current.Close();
                ListaDeClientesSockets.Remove(current);
                Console.WriteLine("Cliente Desconectado ");
                return;
            }
            else if(text == "sincronizar")
            {

            }
            else
            {

                byte[] data = Encoding.ASCII.GetBytes("Parametros incorretos ");
                current.Send(data);

            }

            current.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
        }
    }
}

Cliente:

namespace TCPSocketClient
{
    class Client
    {
        Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        int port = 8000;
        string localhostIP = "127.0.0.1";

        public void TryConnect()
        {
            int tentativas = 0;
            while (!socketClient.Connected)
            {
                try
                {
                    socketClient.Connect(IPAddress.Loopback, port);

                }
                catch
                {
                    tentativas++;
                    Console.Clear();
                    Console.WriteLine("Tentativas de conexão : {0}", tentativas);
                }
            }

            Console.WriteLine("Conenctou");
        }

        public void TrySend()
        {
            //while (true)
            //{
                try
                {
                    Console.WriteLine("Entre com uma mensagem ");
                    //string msg = "horas";
                    //byte[] data = Encoding.ASCII.GetBytes(msg);
                    //socketClient.Send(data);
                    byte[] buff = new byte[1024];
                    int received = socketClient.Receive(buff);
                    byte[] dataReceived = new byte[received];
                    Array.Copy(buff, dataReceived, received);
                    Console.WriteLine("Recebido : " + Encoding.ASCII.GetString(dataReceived));

                }
                catch(SocketException)
                {
                    Console.WriteLine("Servidor desconectado, porfavor reinicie o cliente");
                    return;
                }
            //}
        }
    }
}

0 个答案:

没有答案