예제 #1
0
        /// <summary>
        /// TCP 소켓의 BeginReceive에 등록된 콜백 메소드
        /// </summary>
        /// <param name="ar">BeginReceive에 설정한 인스턴스가 담긴 파라미터</param>
        private void ReceiveCb(IAsyncResult ar)
        {
            try
            {
                var sock     = (Socket)ar.AsyncState;
                var dataSize = sock.EndReceive(ar);

                if (dataSize > 0)
                {
                    Console.WriteLine("\n[TCP] Recv [" + dataSize + "] :  bytes.");
                    var dataAry = new byte[dataSize];
                    Array.Copy(_recvBuffer, 0, dataAry, 0, dataSize);
                    PacketMaker.GetPacket(dataAry, ref _packetQueue);
                    Array.Clear(_recvBuffer, 0, _recvBuffer.Length);
                    while (_packetQueue.Count > 0)
                    {
                        var packet = _packetQueue.Dequeue();
                        Console.WriteLine("Received Packet : " + packet.GetType());
                        ProcessPacket(packet);
                    }
                    sock.BeginReceive(_recvBuffer, 0, _recvBuffer.Length, SocketFlags.None, ReceiveCb, sock);
                }
                else
                {
                    Console.WriteLine("[TCP] Receive no data.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
예제 #2
0
        public static void LogIn(Socket s)
        {
            string id        = String.Empty;
            string pw        = String.Empty;
            int    idMaxSize = 12;

            //Get correct login info
            do
            {
                Console.Write("Enter your ID : ");
                id = Console.ReadLine();
            }while (!IsValidID(id, idMaxSize));

            do
            {
                Console.Write("Enter your PW : ");
                pw = Console.ReadLine();
            }while (!IsValidPW(pw, idMaxSize));

            //Send login info to server
            string loginInfo = id + "#" + pw;

            byte[] loginData = PacketMaker.CreatePacket(PacketMaker.CommandCode.LOGIN, Convert.ToUInt16(loginInfo.Length), Connection.StringToByte(loginInfo));

            Connection.ClientToServer(s, loginData);
        }
예제 #3
0
        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);
        }
예제 #4
0
 private void ReceiveCb(IAsyncResult ar)
 {
     try
     {
         //Console.WriteLine("d");
         var uc       = (UdpClient)ar.AsyncState;
         var remoteEp = new IPEndPoint(IPAddress.Any, 0);
         var dataAry  = uc.EndReceive(ar, ref remoteEp);
         if (dataAry.Length > 0)
         {
             //Console.WriteLine("[UDP] Received data size : " + dataAry.Length);
             PacketMaker.GetPacket(dataAry, ref _packetQueue);
         }
         while (_packetQueue.Count > 0)
         {
             var packet = _packetQueue.Dequeue();
             //Console.WriteLine("Received Packet : " + packet.GetType());
             ProcessHandler(packet);
         }
         uc.BeginReceive(ReceiveCb, uc);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
예제 #5
0
        private void ReceiveCb(IAsyncResult ar)
        {
            try
            {
                var sock     = (Socket)ar.AsyncState;
                int recvSize = sock.EndReceive(ar);

                if (recvSize > 0)
                {
                    //Debug.Log("[TCP] Received data size : " + recvSize);
                    var dataAry = new byte[recvSize];
                    Array.Copy(_recvBuffer, 0, dataAry, 0, recvSize);
                    PacketMaker.GetPacket(dataAry, ref packetQueue);
                    Array.Clear(_recvBuffer, 0, _recvBuffer.Length);
                    //Debug.Log("[TCP] Process was done.");
                }
                else
                {
                    Debug.Log("[TCP] Receive no data.");
                }
                sock.BeginReceive(_recvBuffer, 0, _recvBuffer.Length, SocketFlags.None,
                                  ReceiveCb, sock);
            }
            catch (Exception e)
            {
                Debug.Log(e);
            }
        }
예제 #6
0
        public static void main(TcpClient K, object[] Param_Tab)
        {
            byte[] dll_bytes = (byte[])(Param_Tab[1]);

            try
            {
                DLLFromMemory dll = new DLLFromMemory(dll_bytes);

                PacketMaker P = new PacketMaker();
                P.Type_Packet = PacketType.SUCCESS_LOAD_NATIVE_DLL;
                P.Misc        = new object[] { "Dll was loaded successfully !" };
                Packet_Send Send = new Packet_Send();
                Send.Packet = P;

                lock (K)
                {
                    Send.Send(K.GetStream());
                }
            }
            catch (Exception ex)
            {
                //  MessageBox.Show(ex.ToString());

                PacketMaker P = new PacketMaker();
                P.Type_Packet = PacketType.ERROR_LOAD_NATIVE_DLL;
                P.Misc        = new object[] { ex.ToString() };
                Packet_Send Send = new Packet_Send();
                Send.Packet = P;

                lock (K)
                {
                    Send.Send(K.GetStream());
                }
            }
        }
예제 #7
0
        /// <summary>
        /// TCP로 패킷 배열을 보낸다.
        /// </summary>
        /// <param name="p">인터페이스 상속 패킷 클래스 배열</param>
        public void Send(IPacket[] p)
        {
            try
            {
                // 사이즈 오버헤드에 대한 예외처리 구현이 필요함.
                int           size  = 0;
                List <byte[]> dList = new List <byte[]>();
                for (int i = 0; i < p.Length; ++i)
                {
                    var d = PacketMaker.SetPacket(p[i]);
                    size += d.Length;
                    dList.Add(d);
                }
                byte[] data   = new byte[size];
                int    curIdx = 0;
                foreach (var d in dList)
                {
                    Array.Copy(d, 0, data, curIdx, d.Length);
                    curIdx += d.Length;
                }
                clientTcp.Client.BeginSend(data, 0, data.Length, SocketFlags.None, null, clientTcp.Client);

                for (int i = 0; i < p.Length; ++i)
                {
                    Console.WriteLine("[TCP] Send [{0}] : {1}, Length : {2}", clientTcp.Client.RemoteEndPoint, p[i].GetType(), dList[i].Length);
                }
                dList.Clear();
            }
            catch (Exception e)
            {
                Console.WriteLine("[TCP] Send exception : " + e.ToString());
            }
        }
예제 #8
0
 public async Task Handle(SocketUser user, NetPacket lastPacket)
 {
     lock (user)
     {
         if (user.State.HasHandshakedWithServer)
         {
             Logger.Warn($"User [{user.State.Username}|{user.TcpClient.Client.RemoteEndPoint.ToString()}] is trying"
                         + " to handshake with the server even though they've already done so.");
         }
     }
     await NetData.WritePacketsAsync(user.Stream, PacketMaker.GetPacketFromOpcode(PacketOpcode.AnnounceAlive_Response));
 }
예제 #9
0
 public void Send(IPacket p)
 {
     try
     {
         var d = PacketMaker.SetPacket(p);
         clientUDP.BeginSend(d, d.Length, multicastEP, null, null);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
예제 #10
0
 internal void Send(IPacket p)
 {
     try
     {
         var b = PacketMaker.SetPacket(p);
         udp.BeginSend(b, b.Length, serverEP, null, udp);
     }
     catch (Exception e)
     {
         Debug.Log(e);
     }
 }
예제 #11
0
 internal void Send(IPacket p)
 {
     try
     {
         var b = PacketMaker.SetPacket(p);
         tcp.Client.BeginSend(b, 0, b.Length, SocketFlags.None, null, tcp.Client);
     }
     catch (Exception e)
     {
         Debug.Log(e);
     }
 }
예제 #12
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
            }
예제 #13
0
 /// <summary>
 /// TCP로 패킷을 보낸다.
 /// </summary>
 /// <param name="p">인터페이스 상속 패킷 클라스</param>
 public void Send(IPacket p)
 {
     try
     {
         var data = PacketMaker.SetPacket(p);
         clientTcp.Client.BeginSend(data, 0, data.Length, SocketFlags.None, null, clientTcp.Client);
         Console.WriteLine("[TCP] Send [{0}] : {1}, Length : {2}", clientTcp.Client.RemoteEndPoint, p.GetType(), data.Length);
     }
     catch (Exception e)
     {
         Console.WriteLine("[TCP] Send exception : " + e.ToString());
     }
 }
예제 #14
0
 public static void SendPacket(IPacket p)
 {
     try
     {
         var b = PacketMaker.SetPacket(p);
         socketTcp.BeginSend(b, 0, b.Length, SocketFlags.None, null, socketTcp);
         Debug.Log("Send");
     }
     catch (Exception e)
     {
         Debug.Log(e);
     }
 }
예제 #15
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");
         }
     }
 }
예제 #16
0
        public static void SendMessage()
        {
            string inputMessage      = String.Empty;
            ushort messageStringSize = 0;

            byte[] msgArray = new byte[1024];
            //create Packet
            inputMessage = KeyInputController.inputString;
            Array.Copy(Encoding.UTF8.GetBytes(inputMessage), msgArray, Encoding.UTF8.GetBytes(inputMessage).Length);
            messageStringSize = Convert.ToUInt16(Encoding.UTF8.GetBytes(inputMessage).Length);
            byte[] sendMessagePacket = PacketMaker.CreatePacket(PacketMaker.CommandCode.MESSAGE_TO_SERVER, messageStringSize, msgArray);

            //send Packet to server
            Connection.ClientToServer(Connection.cliSocket, sendMessagePacket);
        }
예제 #17
0
        public static ChatProtocol ServerToClient(Socket s)
        {
            ChatProtocol pt;

            byte[] data = new byte[Marshal.SizeOf(typeof(ChatProtocol))];

            s.Receive(data, data.Length, SocketFlags.None);


            if (!PacketMaker.TryDePacket(data, out pt))
            {
                Console.WriteLine("DePacket Error!");
            }

            return(pt);
        }
예제 #18
0
 private void ReceiveCb(IAsyncResult ar)
 {
     try
     {
         Debug.Log("받는지 확인");
         var uc       = (UdpClient)ar.AsyncState;
         var remoteEp = new IPEndPoint(IPAddress.Any, 0);
         var dataAry  = uc.EndReceive(ar, ref remoteEp);
         if (dataAry.Length > 0)
         {
             //Debug.Log("[UDP] Received data size : " + dataAry.Length);
             PacketMaker.GetPacket(dataAry, ref packetQueue);
         }
         uc.BeginReceive(ReceiveCb, uc);
     }
     catch (Exception e)
     {
         Debug.Log(e);
     }
 }
예제 #19
0
        public async Task ServerListenThreadAction(string hostname, int port)
        {
            var client = default(TcpClient);

            try
            {
                client = new TcpClient(hostname, port);
                Logger.Info($"Connected to [{hostname}:{port}]");

                var stream = client.GetStream();

                Logger.Info($"Sending [{nameof(PacketOpcode.AnnounceAlive)}] packet to server.");
                var announceAlive = PacketMaker.GetPacketFromOpcode(PacketOpcode.AnnounceAlive);
                await NetData.WritePacketsAsync(stream, announceAlive);

                Logger.Info($"Waiting on response...");
                var response = await NetData.ReadPacketAsync(stream, client.ReceiveBufferSize);

                if (response.Opcode == PacketOpcode.AnnounceAlive_Response)
                {
                    Logger.Info($"Received valid {nameof(PacketOpcode.AnnounceAlive_Response)} packet from server.");
                    OnServerConnected?.Invoke();
                }
                else
                {
                    Logger.Error($"Failed handshake with server. Expected [{nameof(PacketOpcode.AnnounceAlive_Response)}] but received [{response.Opcode}] instead.");
                }
            }
            catch (ThreadInterruptedException e)
            {
                Logger.Error($"{nameof(ServerListenThreadAction)} thread was interrupted and connection will be forcibly closed by us.");
            }
            finally
            {
                if (client != null && client.Connected)
                {
                    client.Close();
                }
            }
        }
예제 #20
0
        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);
        }
예제 #21
0
 public static void LogOut(Socket s)
 {
     byte[] logoutData = PacketMaker.CreatePacket(PacketMaker.CommandCode.LOGOUT, 0, Connection.StringToByte("0"));
     Connection.ClientToServer(s, logoutData);
 }