コード例 #1
0
ファイル: Program.cs プロジェクト: eblikes2play/Chat_Client
        public static bool JoinRoom(Socket s, int roomNum)
        {
            byte[] joinRoomRequest
                = PacketMaker.CreatePacket(PacketMaker.CommandCode.JOIN_ROOM, Convert.ToUInt16(roomNum), Connection.StringToByte("0"));

            Connection.ClientToServer(s, joinRoomRequest);
            ChatProtocol joinResult = Connection.ServerToClient(s);

            if (joinResult.command == PacketMaker.CommandCode.JOIN_ROOM_RESULT)
            {
                if (BitConverter.ToInt32(joinResult.variableLengthField, 0) == 1)
                {
                    Console.WriteLine("Join to Room # : " + roomNum);
                    Chat.StartChat(roomNum);
                    return(true);
                }
                else if (BitConverter.ToInt32(joinResult.variableLengthField, 0) == -1)
                {
                    Console.WriteLine("Join Room Failed");
                    return(false);
                }
            }
            else
            {
                Console.WriteLine("Invalid Message from Server");
                return(false);
            }
            return(false);
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: eblikes2play/Chat_Client
        public static bool LogInAccept(Socket s)
        {
            ChatProtocol result = Connection.ServerToClient(s);

            if (result.command == PacketMaker.CommandCode.LOGIN_RESULT)
            {
                if (BitConverter.ToInt32(result.variableLengthField, 0) == 1)
                {
                    Console.WriteLine("Welcome!");
                    return(true);
                }
                else if (BitConverter.ToInt32(result.variableLengthField, 0) == -1)
                {
                    Console.WriteLine("LogIn Failed");
                    return(false);
                }
                else
                {
                    Console.WriteLine(BitConverter.ToInt32(result.variableLengthField, 0));
                    Console.WriteLine("valueB error.");
                    return(false);
                }
            }
            else
            {
                Console.WriteLine("login command error.");
                return(false);
            }
        }
コード例 #3
0
 /// <summary>
 /// Método gatillado al hacer clic en el boton enviar
 /// </summary>
 /// <param name="sender">El sender del evento</param>
 /// <param name="e">Los parametros del evento</param>
 private void buttonSend_Click(object sender, EventArgs e)
 {
     if (textBoxMessage.Text.Length > 0)
     {
         ChatProtocol.sendTextMessage(null, textBoxMessage.Text);
         chatMessageReceived(netUser, textBoxMessage.Text);
         textBoxMessage.Text = "";
     }
 }
コード例 #4
0
 /// <summary>
 /// Método gatillado al presionar una tecla teniendo foco del textBox mensaje
 /// </summary>
 /// <param name="sender">quien envia el evento</param>
 /// <param name="e">los parametros del evento</param>
 private void textBoxMessage_KeyPress(object sender, KeyPressEventArgs e)
 {
     if (e.KeyChar.Equals('\r'))
     {
         if (textBoxMessage.Text.Length > 0)
         {
             ChatProtocol.sendTextMessage(null, textBoxMessage.Text);
             chatMessageReceived(netUser, textBoxMessage.Text);
             textBoxMessage.Text = "";
         }
     }
 }
コード例 #5
0
            public static void BuildInput()
            {
                ConsoleKeyInfo holdKey = new ConsoleKeyInfo();

                //command = null;


                do
                {
                    inputString = command.ToString();
                    command.Clear(); //When the command wasn't a 'stop', clear the request and continue collecting the new input

                    do
                    {
                        holdKey = Console.ReadKey();
                        switch (holdKey.KeyChar)
                        {
                        case '\r':
                            break;

                        case '\b':
                            if (command.Length > 0)
                            {
                                command.Remove(command.Length - 1, 1);
                            }
                            break;

                        default:
                            command.Append(holdKey.KeyChar);
                            break;
                        }
                        wasCharWritten = true;
                    } while (holdKey.KeyChar != '\r');

                    if (!command.ToString().ToUpper().Equals("LEAVE"))
                    {
                        wasStringSended = true;
                    }
                    //On a return key(=enter), stop the loop to check for a "LEAVE" command
                } while (!command.ToString().ToUpper().Equals("LEAVE"));

                //Run this build input until a stop command is received

                wasStopChatted = true;//Need to lock
                byte[] leaveChat = PacketMaker.CreatePacket(PacketMaker.CommandCode.LEAVE_ROOM, 0, Connection.StringToByte("0"));
                Connection.ClientToServer(Connection.cliSocket, leaveChat);
                ChatProtocol leaveResult = Connection.ServerToClient(Connection.cliSocket);



                //signal that a stop command has been fired
            }
コード例 #6
0
 public void GetHeartBeat()
 {
     while (true)
     {
         ChatProtocol heartBeatPacket = Connection.ServerToClient(Connection.cliSocket);
         if (heartBeatPacket.command == 60)
         {
             Console.Write("gotcha hb!");
             byte[] heartBeatResponse = PacketMaker.CreatePacket(PacketMaker.CommandCode.HEARTBEAT_RESULT, 0, Connection.StringToByte("0"));
             Connection.ClientToServer(Connection.cliSocket, heartBeatResponse);
             Console.Write("response to hb");
         }
     }
 }
コード例 #7
0
ファイル: Program.cs プロジェクト: eblikes2play/Chat_Client
        public static int CreateRoom(Socket s)
        {
            int    roomNumber        = -1;
            int    maxRoomNameLength = 20;
            string roomName;

            do
            {
                Console.WriteLine("Enter Room Name");
                roomName = Console.ReadLine();

                if (roomName.Length > maxRoomNameLength)
                {
                    Console.WriteLine("방 이름이 너무 길어양");
                }
            } while (roomName.Length > maxRoomNameLength);

            ushort roomNameLength = Convert.ToUInt16(roomName.Length);

            byte[] newRoomRequest = PacketMaker.CreatePacket(PacketMaker.CommandCode.CREATE_ROOM, roomNameLength, Connection.StringToByte(roomName));
            Connection.ClientToServer(s, newRoomRequest);

            Console.WriteLine(Chat.KeyInputController.wasStopChatted);
            ChatProtocol newRoom = Connection.ServerToClient(s);

            if (newRoom.command == PacketMaker.CommandCode.CREATE_ROOM_RESULT)
            {
                roomNumber = BitConverter.ToInt32(newRoom.variableLengthField, 0);
            }
            else
            {
                Console.WriteLine("command error");
            }

            return(roomNumber);
        }
コード例 #8
0
 public string GetWelcomeMessage(ChatProtocol protocol)
 {
     string path = Config.Get<string>($"Protocols.{protocol.ToString()}", "MotdPath");
     return File.Exists(path) ? File.ReadAllText(path) : GetWelcomeMessage();
 }
コード例 #9
0
        public void init()
        {
            try
            {
                //se inicializa la configuración
                configuration = new Configuration();
                configuration.NetData.OpSystem = NetLayer.OpSystemType.WINMOBILE5POCKETPC;

                //Configuración de controles
                statusControl.connectNotification    += connect;
                statusControl.disConnectNotification += disconnect;
                chatControl.NetUser = configuration.NetUser;

                //Configuración de subprotocolos
                SubProtocolList subProtocols = new SubProtocolList();
                chatProtocol = new ChatProtocol(chatControl);
                subProtocols.add(SubProtocol.Chat.Types.CHATPROTOCOL, chatProtocol);
                fileTransferProtocol = new FileTransferProtocol(fileControl, fileListControl, createFileData());
                subProtocols.add(SubProtocol.FileTransfer.Types.FILETRANSFERPROTOCOL, fileTransferProtocol);
                pingProtocol = new PingProtocol(this);
                subProtocols.add(SubProtocol.Ping.Types.PINGPROTOCOL, pingProtocol);

                chatControl.ChatProtocol             = chatProtocol;
                fileListControl.FileTransferProtocol = fileTransferProtocol;

                //se crea el objeto de comunicación
                communication = new Communication(configuration, subProtocols, null);

                //Se setean los handlers de los eventos de usuarios
                communication.addUserEvent          += netUserControl.addUserHandler;
                communication.addUserEvent          += fileTransferProtocol.sendFileListRequest;
                communication.refreshUserEvent      += netUserControl.refreshUserHandler;
                communication.refreshLocalUserEvent += netUserControl.refreshLocalUserHandler;
                communication.removeUserEvent       += netUserControl.removeUserHandler;
                communication.removeUserEvent       += fileListControl.removeFileList;

                //Se setean los handlers de los eventos de conexion
                communication.connectEvent       += statusControl.connectHandler;
                communication.connectEvent       += fileTransferProtocol.start;
                communication.connectingEvent    += statusControl.connectingHandler;
                communication.disconnectEvent    += statusControl.disconnectHandler;
                communication.disconnectEvent    += fileTransferProtocol.stop;
                communication.disconnectEvent    += clear;
                communication.disconnectingEvent += statusControl.disconnectingHandler;
                communication.reconnectingEvent  += statusControl.reconnectingHandler;
                communication.reconnectingEvent  += fileTransferProtocol.stop;
                communication.reconnectingEvent  += clear;

                //se setean los handlers de los eventos del sistema
                communication.exceptionEvent      += exceptionHandler;
                communication.netInformationEvent += log;

                //iniciamos el consumidor de eventos
                communication.startEventConsumer();
            }
            catch (Exception e)
            {
                MessageBox.Show("Ups!: " + e.Message);
                Close();
            }
        }
コード例 #10
0
        public void init()
        {
            try
            {
                //incializamos una configuracion
                configuration = new Configuration();

                //OS
                configuration.NetData.OpSystem = OpSystemType.WIN7;

                //configuramos los controles
                statusControl.connectNotification    += connect;
                statusControl.disConnectNotification += disconnect;
                chatControl.NetUser = configuration.NetUser;

                //configuramos los sub protocolos
                SubProtocolList subProtocols = new SubProtocolList();
                chatProtocol = new ChatProtocol(chatControl);
                subProtocols.add(SubProtocol.Chat.Types.CHATPROTOCOL, chatProtocol);
                fileTransferProtocol = new FileTransferProtocol(fileControl, fileListControl, createFileData());
                subProtocols.add(SubProtocol.FileTransfer.Types.FILETRANSFERPROTOCOL, fileTransferProtocol);
                pingProtocol = new PingProtocol(this);
                subProtocols.add(SubProtocol.Ping.Types.PINGPROTOCOL, pingProtocol);

                chatControl.ChatProtocol             = chatProtocol;
                fileListControl.FileTransferProtocol = fileTransferProtocol;

                //Configuramos los tipos de mensajes que no pertenecen a subprotocolos
                MessageTypeList messageTypeList = new MessageTypeList();

                //se crea el objeto de comunicación
                communication = new Communication(configuration, subProtocols, messageTypeList);

                //Se setean los handlers de los eventos de usuarios
                communication.addUserEvent          += netUserControl.addUserHandler;
                communication.addUserEvent          += fileTransferProtocol.sendFileListRequest;
                communication.addUserEvent          += networkGraphControl.addUserHandler;
                communication.refreshUserEvent      += netUserControl.refreshUserHandler;
                communication.refreshUserEvent      += networkGraphControl.refreshUserHandler;
                communication.refreshLocalUserEvent += netUserControl.refreshLocalUserHandler;
                communication.refreshLocalUserEvent += networkGraphControl.refreshLocalUserHandler;
                communication.removeUserEvent       += netUserControl.removeUserHandler;
                communication.removeUserEvent       += fileListControl.removeFileList;
                communication.removeUserEvent       += networkGraphControl.removeUserHandler;

                //Se setean los handlers de los eventos de conexion
                communication.connectEvent       += statusControl.connectHandler;
                communication.connectEvent       += fileTransferProtocol.start;
                communication.connectingEvent    += statusControl.connectingHandler;
                communication.disconnectEvent    += statusControl.disconnectHandler;
                communication.disconnectEvent    += fileTransferProtocol.stop;
                communication.disconnectEvent    += clear;
                communication.disconnectingEvent += statusControl.disconnectingHandler;
                communication.reconnectingEvent  += statusControl.reconnectingHandler;
                communication.reconnectingEvent  += fileTransferProtocol.stop;
                communication.reconnectingEvent  += clear;

                //Se setean los handlers de los eventos del sistems
                communication.exceptionEvent      += exceptionHandler;
                communication.netInformationEvent += netInformationHandler;

                //iniciamos el consumidor de eventos
                communication.startEventConsumer();

                //Se abre el archivo para log
                FileInfo t = new FileInfo("CommLayer.log");
                Tex = t.AppendText();
            }
            catch (Exception e)
            {
                MessageBox.Show("Ups!: " + e.Message);
                Close();
            }
        }
コード例 #11
0
 protected override void OnSessionNewMessage(WebSocketSession session, WebSocketMessage message)
 {
     if (message.Opcode == WebSocketOpcode.Text)
     {
         string       m           = Encoding.UTF8.GetString(message.Message);
         ChatProtocol chatMessage = JsonConvert.DeserializeObject <ChatProtocol>(m);
         if (string.IsNullOrEmpty(chatMessage.UserName))
         {
             session.Close("UserName missed", WebSocketCloseStatusCode.InternalServerError);
             Sessions.Remove(session.SessionID);
             return;
         }
         if (chatMessage.CommandType == "Login")
         {
             if (Room.ContainsUser(chatMessage.UserName))
             {
                 chatMessage.CommandType = "Error";
                 chatMessage.Message     = "User have been already in chatroom";
                 session.Close("User have already logined", WebSocketCloseStatusCode.InternalServerError);
                 Sessions.Remove(session.SessionID);
                 return;
             }
             else
             {
                 Room.AddUser(chatMessage.UserName, session.RemoteEndpoint);
                 var remotelist = Room.RemoteEndpointList;
                 foreach (var remote in remotelist)
                 {
                     WebSocketSession s = Sessions[remote];
                     if (s != null)
                     {
                         if (!s.Send(m))
                         {
                             Sessions.Remove(session.SessionID);
                             string user = Room.GetUser(remote);
                             if (!string.IsNullOrEmpty(user))
                             {
                                 Room.RemoveUser(user);
                             }
                         }
                     }
                 }
                 return;
             }
         }
         else if (chatMessage.CommandType == "Message")
         {
             var remotelist = Room.RemoteEndpointList;
             foreach (var remote in remotelist)
             {
                 WebSocketSession s = Sessions[remote];
                 if (s != null)
                 {
                     if (!s.Send(m))
                     {
                         Sessions.Remove(session.SessionID);
                         string user = Room.GetUser(remote);
                         if (!string.IsNullOrEmpty(user))
                         {
                             Room.RemoveUser(user);
                         }
                     }
                 }
             }
         }
         else
         {
             return;
         }
     }
 }