Ejemplo n.º 1
0
        private void ReceiveData(IAsyncResult asyncResult)
        {
            try
            {
                byte[] data;

                Packet receivedData = new Packet(dataStream);

                Packet sendData = new Packet();

                IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0);

                EndPoint epSender = clients;

                serverSocket.EndReceiveFrom(asyncResult, ref epSender);

                sendData.ChatDataId = receivedData.ChatDataId;
                sendData.ChatName   = receivedData.ChatName;

                switch (receivedData.ChatDataId)
                {
                case DataId.Message:
                    sendData.ChatMessage = string.Format("{0}: {1}", receivedData.ChatName, receivedData.ChatMessage);
                    break;

                case DataId.LogIn:
                    Client client = new Client();
                    client.endPoint = epSender;
                    client.name     = receivedData.ChatName;

                    clientList.Add(client);

                    sendData.ChatMessage = string.Format("-- {0} is online --", receivedData.ChatName);
                    break;

                case DataId.LogOut:
                    foreach (Client c in clientList)
                    {
                        if (c.endPoint.Equals(epSender))
                        {
                            clientList.Remove(c);
                            break;
                        }
                    }

                    sendData.ChatMessage = string.Format("-- {0} has gone offline --", receivedData.ChatName);
                    break;
                }

                data = sendData.GetDataStream();

                foreach (Client client in clientList)
                {
                    if (client.endPoint != epSender || sendData.ChatDataId != DataId.LogIn)
                    {
                        serverSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, client.endPoint, new AsyncCallback(SendData), client.endPoint);
                    }
                }

                serverSocket.BeginReceiveFrom(dataStream, 0, dataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender);

                updateStatusDelegate(sendData.ChatMessage);
            }
            catch (Exception ex)
            {
                MessageBox.Show("ReceiveData Error: " + ex.Message, "Server Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }