Ejemplo n.º 1
0
        private static readonly handleClient[] clients = new handleClient[maxPlayers]; //Se crea el objeto de clientes

        static void Main(string[] args)
        {
            serverSocket = new TcpListener(IPAddress.Any, 2000); //Se crea el Socket del Servidor
            clientSocket = default(Socket);                      //Se crea el Socket de Cliente
            serverSocket.Start();                                //Inicia el Socket Cliente

            while (true)
            {
                Console.WriteLine("Esperando Jugadores...");
                clientSocket = serverSocket.AcceptSocket(); //Cuando se conecta un jugador
                Console.WriteLine("Jugador Conectado");
                int i = 0;
                for (i = 0; i < maxPlayers; i++)                                              //Recorremos i, que llega hasta el maximo de jugadores
                {
                    if (clients[i] == null)                                                   //Si el cliente en la posicion i no existe
                    {
                        (clients[i] = new handleClient()).startClient(clientSocket, clients); //Se Conecta el cliente, siendo i su posicion
                        break;
                    }
                }

                if (i == maxPlayers)                                                      //Si ya se conectaron el maximo de jugadores
                {
                    StreamWriter ots = new StreamWriter(new NetworkStream(clientSocket)); //Se crea ots que escribe por el socket de clientes
                    ots.AutoFlush = true;                                                 //Flusheo automatico
                    ots.WriteLine("Ya se alcanzó el maximo de jugadores");
                    ots.Close();
                    clientSocket.Close();
                }
            }
        }
Ejemplo n.º 2
0
        private void InitSocket()
        {
            server       = new TcpListener(IPAddress.Any, 9999);
            clientSocket = default(TcpClient);
            server.Start();
            DisplayText(">> Server Started");

            while (true)
            {
                try
                {
                    counter++;
                    clientSocket = server.AcceptTcpClient();
                    DisplayText(">> Accept connection from client");

                    NetworkStream stream    = clientSocket.GetStream();
                    byte[]        buffer    = new byte[1024];
                    int           bytes     = stream.Read(buffer, 0, buffer.Length);
                    string        user_name = Encoding.Unicode.GetString(buffer, 0, bytes);
                    user_name = user_name.Substring(0, user_name.IndexOf("$"));

                    clientList.Add(clientSocket, user_name);

                    // send message all user
                    SendMessageAll(user_name + " Joined ", "", false);

                    handleClient h_client = new handleClient();
                    h_client.OnReceived     += new handleClient.MessageDisplayHandler(OnReceived);
                    h_client.OnDisconnected += new handleClient.DisconnectedHandler(h_client_OnDisconnected);
                    h_client.startClient(clientSocket, clientList);
                }
                catch (SocketException se)
                {
                    Trace.WriteLine(string.Format("InitSocket - SocketException : {0}", se.Message));
                    break;
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("InitSocket - Exception : {0}", ex.Message));
                    break;
                }
            }

            clientSocket.Close();
            server.Stop();
        }
Ejemplo n.º 3
0
        private void InitSocket()
        {
            server       = new TcpListener(IPAddress.Any, 9999);
            clientSocket = default(TcpClient);
            server.Start();
            DisplayText(">> Server Start!! <<");

            while (true)
            {//클라이언트 요청 받음 -> 소켓과 닉네임 저장
                try
                {
                    clientSocket = server.AcceptTcpClient();
                    clientNum.Add(clientSocket, counter);
                    fileStrm = new FileStream(Environment.CurrentDirectory + "\\Server\\bin\\Debug\\" + counter.ToString() + ".jpg", FileMode.Create, FileAccess.Write);
                    counter++;  //클라이언트 수 추가
                    DisplayText(">> Accept connection from client");

                    /////////////////////////////////   닉네임 저장   ////////////////////////////////
                    ClientProfile clientProfile = new ClientProfile();  //패킷을 위한 객체
                    stream = clientSocket.GetStream();
                    int    bytes    = stream.Read(this.readbuffer, 0, this.readbuffer.Length);
                    string nickName = null;
                    Packet packet   = (Packet)Packet.Deserialize(this.readbuffer);
                    clientProfile = (ClientProfile)Packet.Deserialize(this.readbuffer);
                    nickName      = clientProfile.nickName;
                    clientList.Add(clientSocket, nickName);    //클라이언트 리스트에 새로 접속한 클라이언트 소켓과 닉네임 저장
                    clients.Add(clientSocket);
                    nickNameList.Add(nickName);
                    clientScore.Add(counter - 1, 0);
                    //////////////////////////////////////////////////////////////////////////////////

                    /////////   새로 접속한 클라이언트에게 클라이언트 넘버 및 기존 닉네임들 전송   /////////
                    Init init = new Init();
                    init.clinetNumber = clientNum[clientSocket];
                    init.Type         = (int)PacketType.초기화;
                    for (int i = 0; i <= clientNum[clientSocket]; i++)
                    {
                        init.nickNameList[i] = (string)nickNameList[i];
                    }
                    Packet.Serialize(init).CopyTo(this.sendbuffer, 0);
                    stream.Write(this.sendbuffer, 0, this.sendbuffer.Length);
                    stream.Flush();
                    resetBuffer(sendbuffer);
                    ///////////////////////////////////////////////////////////////////////////////////////

                    /*닉네임 추가 -> 라벨 추가하기 위해서 6.13 */
                    foreach (var pair in clientList)
                    {
                        TcpClient client = pair.Key as TcpClient;

                        NickName nick_name = new NickName();
                        nick_name.client_sum = counter; //추가된 클라이언트수
                        nick_name.Type       = (int)PacketType.닉네임;
                        for (int i = 0; i <= clientNum[clientSocket]; i++)
                        {
                            nick_name.nickNameList[i] = (string)nickNameList[i];
                        }

                        NetworkStream stream = client.GetStream();
                        Packet.Serialize(nick_name).CopyTo(this.sendbuffer, 0);

                        stream.Write(this.sendbuffer, 0, this.sendbuffer.Length);
                        this.stream.Flush();
                        resetBuffer(sendbuffer);
                    }

                    // send message all user
                    SendMessageAll(nickName + "님이 접속하셨습니다.", "", false);   //서버한테

                    //handleClient클래스는 클라이언트들을 다루는 클래스
                    handleClient h_client = new handleClient();
                    h_client.OnRequest      += new handleClient.ClientRequestHandler(this.OnRequest);         //클라이언트 요청 이벤트 핸들러 추가.
                    h_client.OnDisconnected += new handleClient.DisconnectedHandler(h_client_OnDisconnected); //연결 끊겼을 때
                    h_client.startClient(clientSocket, clientList, clientNum);
                }
                catch (SocketException se)  //소켓 연결에서의 예외 발생
                {
                    Trace.WriteLine(string.Format("InitSocket - SocketException : {0}", se.Message));
                    break;
                }
                catch (Exception ex)    //그 외의 예외 발생
                {
                    Trace.WriteLine(string.Format("InitSocket - Exception : {0}", ex.Message));
                    break;
                }
            }

            clientSocket.Close();
            server.Stop();
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            //the creation of a client list
            List <DataBase> clientInfoListDB = new List <DataBase>();

            //intantiate new client databse
            DataBase newClientDB = new DataBase();

            //create new mutex for ciritcal region access (file write and database read)
            m = new Mutex();

            //hostname
            String strHostName = string.Empty;

            //hardcoded port
            int port = 5001;

            //get hostname of computer
            strHostName = Dns.GetHostName();
            Console.WriteLine("Host Name: {0}", strHostName);

            //get IPV4 addresses via loop
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);

            //loop through each IP and get the first one
            foreach (IPAddress ip in ipEntry.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    addr = ip;
                    Console.WriteLine("IP Address: {0} ", addr.ToString());
                    break;
                }
            }

            //create listener server
            TcpListener server = new TcpListener(addr, port); //ipv4
            TcpClient   client = default(TcpClient);

            //convert IP address to string (for ease)
            Console.WriteLine("Port: {0} ", port.ToString());

            //load all file info into list
            if (File.Exists(clientFile))
            {
                using (System.IO.StreamReader inputStream = new System.IO.StreamReader(clientFile))
                {
                    while (!inputStream.EndOfStream)
                    {
                        string   stringToSplit = inputStream.ReadLine();
                        string[] arrayOfSplits = stringToSplit.Split(new char[] { '*' });
                        clientInfoListDB.Add(new DataBase {
                            MemberID = Convert.ToInt32(arrayOfSplits[0]), FirstName = arrayOfSplits[1], LastName = arrayOfSplits[2], DateOfBirth = arrayOfSplits[3], isEdit = 0
                        });
                        idNumber = clientInfoListDB.Count;
                    }
                }
            }

            //error checking for server start failure
            try
            {
                server.Start();
                Console.WriteLine("Server has started...");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.Read();
            }

            //while loop to always listen for incoming client data
            while (true)
            {
                try
                {
                    client         = server.AcceptTcpClient(); //accept connection from client
                    client.NoDelay = true;
                }
                catch (Exception e)
                {
                    Console.WriteLine("ERROR " + e.ToString());
                }

                handleClient Newclient = new handleClient();
                Newclient.startClient(client, clientInfoListDB, m);
            }
        }