コード例 #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("---SERVER CHAT---\n");
            IPEndPoint  ipe      = new IPEndPoint(IPAddress.Any, 9050);
            TcpListener maychu   = new TcpListener(ipe);
            TcpClient   maykhach = default(TcpClient);
            int         counter  = 0;

            maychu.Start();
            while (true)
            {
                counter  = counter + 1;
                maykhach = maychu.AcceptTcpClient();
                StreamReader srUsername = new StreamReader(maykhach.GetStream());
                string       dataclient = srUsername.ReadLine();
                clientsList.Add(dataclient, maykhach);
                broadcast(dataclient + " Online", dataclient, false);
                Console.WriteLine(dataclient + " Joined chat");
                handleClient client = new handleClient();
                client.startClient(maykhach, dataclient, clientsList);
            }
            maychu.Stop();
            maykhach.Close();
            Console.ReadLine();
        }
コード例 #2
0
        static void Main(string[] args)
        {
            TcpListener serverSocket = new TcpListener(8888);
            TcpClient   clientSocket = default(TcpClient);

            serverSocket.Start();
            Console.WriteLine(" >> Server up");
            //a default room is created immediately upon running the app, for convenience
            Room defaultRoom = new Room("Default room");

            roomList.Add(defaultRoom);
            //a separate thread for the console commands
            Thread com = new Thread(Command);

            com.Start();

            while ((!dying))
            {
                clientSocket = serverSocket.AcceptTcpClient();

                byte[] bytesReceived = new byte[10025];
                string username      = "";

                /*a character '$' is used as a terminator for every client-server message,
                 * also the message always starts with either "I:" or "M:", which specifies whether
                 * it's a text message from the client, or a background information for the app*/
                NetworkStream networkStream = clientSocket.GetStream();
                networkStream.Read(bytesReceived, 0, bytesReceived.Length);
                username = Encoding.Unicode.GetString(bytesReceived);
                username = username.Substring(0, username.IndexOf("$"));
                username = username.Substring(2, username.Length - 2);
                try
                {
                    clientsList.Add(username, clientSocket);
                    NetworkStream unameStream = clientSocket.GetStream();
                    byte[]        unameBytes  = Encoding.Unicode.GetBytes("I:UrOK$");
                    unameStream.Write(unameBytes, 0, unameBytes.Length);
                    unameStream.Flush();
                    //there's a new thread created for every client, handling them separately
                    handleClient client = new handleClient();
                    client.startClient(clientSocket, username, clientsList);
                }
                //handled case with an existing username, which triggers "can't add it to the hashtable" exception
                catch
                {
                    NetworkStream unameStream = clientSocket.GetStream();
                    byte[]        unameBytes  = Encoding.Unicode.GetBytes("I:UsernameExists$");
                    unameStream.Write(unameBytes, 0, unameBytes.Length);
                    unameStream.Flush();
                    unameStream.Dispose();
                    clientSocket.Close();
                    continue;
                }
            }

            Console.WriteLine(" >> SHUTDOWN");
            Console.ReadLine();
        }
コード例 #3
0
 public void SocketServerPollingLoop()
 {
     if (serverSocket.Pending() == true)
     {
         clientSocket = serverSocket.AcceptTcpClient();
         handleClient client = new handleClient();
         client.startClient(clientSocket);
     }
 }
コード例 #4
0
ファイル: Program.cs プロジェクト: masturmind/messerver
        static void Main(string[] args)
        {
            TcpListener serverSocket = new TcpListener(8888);
            TcpClient   clientSocket = default(TcpClient);

            serverSocket.Start();
            Console.WriteLine(" >> Server up");
            Thread com = new Thread(Command);

            com.Start();

            while ((!dying))
            {
                clientSocket = serverSocket.AcceptTcpClient();

                // Thread.Sleep(500);
                byte[] bytesReceived = new byte[10025];
                string username      = "";


                NetworkStream networkStream = clientSocket.GetStream();
                networkStream.Read(bytesReceived, 0, bytesReceived.Length);
                username = Encoding.Unicode.GetString(bytesReceived);
                username = username.Substring(0, username.IndexOf("$"));
                username = username.Substring(2, username.Length - 2);
                try
                {
                    clientsList.Add(username, clientSocket);
                    NetworkStream errorStream = clientSocket.GetStream();
                    byte[]        errorBytes  = Encoding.Unicode.GetBytes("I:UrOK$");
                    errorStream.Write(errorBytes, 0, errorBytes.Length);
                    errorStream.Flush();
                }
                catch
                {
                    NetworkStream errorStream = clientSocket.GetStream();
                    byte[]        errorBytes  = Encoding.Unicode.GetBytes("I:UsernameExists$");
                    errorStream.Write(errorBytes, 0, errorBytes.Length);
                    errorStream.Flush();
                    errorStream.Dispose();
                    clientSocket.Close();
                    continue;
                }

                broadcast("[INFO] " + username + " joined", username, true);
                Console.WriteLine(" >> " + username + " joined the chat room");     //rooms
                handleClient client = new handleClient();
                client.startClient(clientSocket, username, clientsList);
            }

            Console.WriteLine(" >> SHUTDOWN");
            Console.ReadLine();
        }
コード例 #5
0
        private void InitSocket()
        {
            PORT         = Int32.Parse(txtPNumber.Text.Trim());
            server       = new TcpListener(IPAddress.Any, PORT);
            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();
        }
コード例 #6
0
        private void BackgroundMethod()
        {
            while (true)
            {
                clients += 1;

                Dispatcher.Invoke(() =>
                {
                    lblConnections.Content = "Conexões: " + ListaClientes.Count;
                });
                try
                {
                    clientSocket = server.AcceptTcpClient();

                    byte[] bytesFrom      = new byte[1024];
                    string dataFromClient = null;

                    clientSocket.ReceiveBufferSize = 1024;
                    clientSocket.SendBufferSize    = 1024;
                    NetworkStream networkStream = clientSocket.GetStream();
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                    dataFromClient = Encoding.UTF8.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    if (ListaClientes.Contains(dataFromClient))
                    {
                        ListaClientes.Add(dataFromClient + i, clientSocket);
                        i++;
                    }
                    else
                    {
                        ListaClientes.Add(dataFromClient, clientSocket);
                    }
                    broadcast(dataFromClient + " entrou no chat.", dataFromClient, false);
                    Dispatcher.Invoke(() =>
                    {
                        txtBoxLog.AppendText("\n" + dataFromClient + " Entrou no chat. ");
                    });

                    handleClient client = new handleClient();
                    client.startClient(clientSocket, dataFromClient, ListaClientes);
                    BackgroundMethod();
                }
                catch
                {
                    //
                }
            }
        }
コード例 #7
0
    static void Main(string[] args)
    {
        IPAddress   ip           = IPAddress.Parse("127.0.0.1");
        TcpListener ServerSocket = new TcpListener(ip, 14000);

        ServerSocket.Start();
        Console.WriteLine("Server started.");
        while (true)
        {
            TcpClient clientSocket = ServerSocket.AcceptTcpClient();
            Console.WriteLine($"client connected: {clientSocket.Client.RemoteEndPoint}");
            lock (_lock) clients.Add(clientSocket);
            handleClient client = new handleClient();
            client.startClient(clientSocket);
            Console.WriteLine($"{GetClientCount()} clients connected");
        }
    }
コード例 #8
0
ファイル: ServerChat.cs プロジェクト: sooyeon330/SoketProgram
        private void InitSocket()
        {
            server       = new TcpListener(IPAddress.Any, port); // 서버 접속 IP, 포트
            clientSocket = default(TcpClient);                   // 소켓 설정
            server.Start();                                      // 서버 시작

            DisplayText(">> Server Started");
            //DisplayText(IPAddress.Any.ToString());

            while (true)
            {
                try
                {
                    counter++;                               // Client 수 증가
                    clientSocket = server.AcceptTcpClient(); // 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("$")); // client 사용자 명

                    DisplayText(">> " + user_name + "님이 접속하였습니다");
                    clientList.Add(clientSocket, user_name);               // cleint 리스트에 추가

                    SendMessageAll(user_name + " 님이 입장하셨습니다.", "", false); // 모든 client에게 메세지 전송

                    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) { break; }
                catch (Exception ex) { break; }
            }
            if (clientSocket != null)
            {
                clientSocket.Close();                      // client 소켓 닫기
            }
            DisplayText(">>Server End");
            server.Stop(); // 서버 종료
        }
コード例 #9
0
        private void ServerWorking(CancellationToken ct) //Зрительная память
        {
            int counter = 0;

            while (working)
            {
                try
                {
                    if (ct.IsCancellationRequested)
                    {
                        return;
                    }
                    counter     += 1;
                    clientSocket = server.AcceptTcpClient();
                    tbLog.Invoke(new Action(() => tbLog.Text += "\nКлиент №:" + Convert.ToString(counter) + " подключился"));
                    handleClient client = new handleClient();
                    client.startClient(clientSocket);
                }
                catch (Exception)
                {
                    working = false;
                }
            }
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: Garlimidon/GregoryChat
 static void Main(string[] args)
 {
     TcpListener serverSocket = new TcpListener(8888);
     TcpClient clientSocket = default(TcpClient);
     int counter = 0;
     serverSocket.Start();
     Console.WriteLine("Servidor iniciado...");
     while (true)
     {
         counter += 1;
         clientSocket = serverSocket.AcceptTcpClient();
         byte[] bytesFrom = new byte[10025];
         string dataFromClient = null;
         NetworkStream networkStream = clientSocket.GetStream();
         networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
         dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
         dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
         clientsList.Add(dataFromClient, clientSocket);
         broadcast(dataFromClient, dataFromClient, false);
         Console.WriteLine(dataFromClient + " Se ha conectado");
         handleClient client = new handleClient();
         client.startClient(clientSocket, dataFromClient, clientsList);
     }
 }
コード例 #11
0
        static void Main(string[] args)
        {
            queue = new Queue <string>();
            count = 0;
            //Then create our Endpoint instance
            endpoint = new SparqlRemoteUpdateEndpoint(ONT_SENSE_URL);

            TcpListener ServerSocket = new TcpListener(PORT);

            ServerSocket.Start();
            Console.WriteLine("OntSense API started on Port " + PORT + ", with " + ONT_SENSE_URL + " Server...");
            TcpClient    clientSocket = ServerSocket.AcceptTcpClient();
            handleClient client       = new handleClient();

            client.startClient(clientSocket);
            while (true)
            {
                string auxString = "";

                lock (queue)
                {
                    if (queue.Count > 0)
                    {
                        auxString = queue.Dequeue();
                    }
                    else
                    {
                        Thread.Yield();
                    }
                }
                if (!auxString.Equals(""))
                {
                    endpoint.Update(auxString);
                }
            }
        }
コード例 #12
0
ファイル: TcpServer.cs プロジェクト: kmroczek11/C-Sharp
        private void bwConnection_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker  = sender as BackgroundWorker;
            IPAddress        adresIP = null;

            try
            {
                adresIP = IPAddress.Parse(tbHostAddress.Text);
            }
            catch
            {
                MessageBox.Show("Błędny format adresu IP!", "Błąd");
                return;
            }

            int port = System.Convert.ToInt16(nUDPort.Value);

            try
            {
                server = new TcpListener(adresIP, port);

                server.Start();

                lbMessage.Invoke(new MethodInvoker(delegate
                {
                    lbMessage.Items.Add("[SERVER]Oczekiwanie na połączenie...");
                    bStart.Enabled = false;
                }));

                while (worker.CancellationPending != true)
                {
                    try
                    {
                        TcpClient    clientSocket = server.AcceptTcpClient();
                        handleClient client       = new handleClient(this);
                        IPEndPoint   IP           = (IPEndPoint)clientSocket.Client.RemoteEndPoint;
                        client.startClient(clientSocket);
                        clients.Add(client);
                        lbNumberOfClients.Invoke(new MethodInvoker(delegate
                        {
                            lbNumberOfClients.Text = clients.Count.ToString();
                        }));
                        lbMessage.Invoke(new MethodInvoker(delegate
                        {
                            lbMessage.Items.Add("[" + IP.ToString() + "]: Nawiązano połączenie.");
                            btSend.Enabled = true;
                            bStop.Enabled  = true;
                        }));
                    }

                    catch (SocketException)
                    {
                        Console.WriteLine("Koniec");
                        //client.
                    }
                }
                Console.WriteLine("Koniec połączenia.");
                e.Cancel = true;
            }

            catch (Exception ex)
            {
                lbMessage.Invoke(new MethodInvoker(delegate { lbMessage.Items.Add("[SERVER]Błąd inicjacji serwera!"); }));
                MessageBox.Show(ex.ToString(), "Błąd.");
            }
        }
コード例 #13
0
        // new connection handler
        public void joinClient()
        {
            // listning for new client connection
            while (true)
            {
                try
                {
                    clientSocket = serverSocket.AcceptTcpClient();

                    // prawidlowe rozwiazanie to
                    // byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
                    byte[] bytesFrom      = new byte[10025];
                    string dataFromClient = null;

                    NetworkStream networkStream = clientSocket.GetStream();
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));

                    // estabilishing new connection
                    try
                    {
                        clientsList.Add(dataFromClient, clientSocket);
                        mvp(true);
                        value = "> " + dataFromClient + " joined lobby (" + label3.Text + " zombies online)\r\n";
                        broadcast(dataFromClient + " joined lobby (" + label3.Text + " zombies online)\r\n", dataFromClient, false);
                        msg();

                        handleClient client = new handleClient();
                        client.startClient(clientSocket, dataFromClient, clientsList, this);
                    }
                    catch
                    {
                        value = "> " + dataFromClient + " tried connect to lobby (disconnected -- same nick)\r\n";
                        // message that sad zombie!
                        Byte[] broadcastBytes = null;
                        broadcastBytes = Encoding.ASCII.GetBytes(dataFromClient + " tried connect to lobby (disconnected -- same nick)\r\n");
                        networkStream.Write(broadcastBytes, 0, broadcastBytes.Length);
                        // + rest
                        broadcast(dataFromClient + " tried connect to lobby (disconnected -- same nick)\r\n", "", false);
                        msg();
                        clientSocket.Client.Disconnect(true);
                    }
                }
                catch (Exception ex)
                {
                    value = ex.ToString();
                    msg();
                }
            }

            // server crashed, should never happen
            value = ">> sLanCS Server stopped ...\r\n";
            msg();
            if (clientSocket.Connected)
            {
                clientSocket.Client.Disconnect(true);
            }
            if (serverSocket.Server.Connected)
            {
                serverSocket.Server.Disconnect(true);
            }
            button1.Enabled = true;
            label1.Visible  = false;
            label3.Visible  = false;
        }
コード例 #14
0
ファイル: Form1.cs プロジェクト: ainochi-kor/HowToCSharp
        private void InitSocket()
        {
            try
            {
                tbxLocalIpAddress.Text =
                    Regex.Replace(tbxLocalIpAddress.Text, @"[^0-9].[^0-9].[^0-9].[^0-9]", "");
                tbxPort.Text = Regex.Replace(tbxPort.Text, @"[^0-9]", "");
                if (tbxLocalIpAddress.Text == "" || tbxPort.Text == "")
                {
                    throw new Exception();
                }
                TcpListner = new TcpListener(IPAddress.Parse(tbxLocalIpAddress.Text.Trim()), Int32.Parse(tbxPort.Text));
                TcpClient = default(TcpClient);
                TcpListner.Start();
                DisplayText(">> server Started");
                while (true)
                {
                    try
                    {
                        counter++;//무슨 기능이 있는지 잘 모르겠음.
                        TcpClient = TcpListner.AcceptTcpClient();

                        this.Invoke(new DeligateGetClientIP(GetClientIP));

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

                        clientList.Add(TcpClient, channel);

                        ipPoint = (IPEndPoint)_tcpClient.Client.RemoteEndPoint;
                        ClientIP = ipPoint.Address.ToString();
                        SendMessageAll(ClientIP + ":" + ipPoint.Port + "/", channel, false);

                        handleClient h_client = new handleClient();
                        h_client.OnReceived += new handleClient.MessageDisplayHandler(OnReceived);
                        h_client.OnDisconnected += new handleClient.DisconnectedHandler(HandlerClientsOnDisconnected);
                        h_client.startClient(TcpClient, clientList);

                    }
                    catch (SocketException se)
                    {
                        MessageBox.Show(se.ToString());
                        throw new Exception();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                        throw new Exception();
                    }
                }
                TcpClient.Close();
                TcpListner.Stop();
            }
            catch
            {
                MessageBox.Show("Local IP Address 또는 Port 번호가 올바르지 않습니다.");
                this.Invoke(new DeligateButtonChange(ButtonStatusChange));
            }
        }
コード例 #15
0
        static void Main(string[] args)
        {
            // Set up the connection
            Int32     port      = 13000;
            IPAddress localAddr = IPAddress.Parse("172.31.18.58");

            // *** Loopback can be uncommented out for testing on local machine ***
            // just make sure you comment out the IP above

            //IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            // get the socket information
            TcpListener serverSocket = new TcpListener(localAddr, port);
            TcpClient   clientSocket = default(TcpClient);

            // start listening for conenctions
            serverSocket.Start();
            Console.WriteLine("Tic Tac Toe Server Started ....");

            // Always listen for incoming connections and when they are successful
            // creates a new thread for the incoming connection
            while ((true))
            {
                try
                {
                    // Accepts the user's connection
                    clientSocket = serverSocket.AcceptTcpClient();
                    byte[] bytesFrom      = new byte[clientSocket.ReceiveBufferSize];
                    string dataFromClient = null;

                    NetworkStream stream = clientSocket.GetStream();
                    stream.Read(bytesFrom, 0, bytesFrom.Length);
                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("|"));
                    Console.WriteLine("dataFromClient   =  " + dataFromClient);

                    // If there is a duplicate user in the client list, send an error message
                    // and continue listening but don't create the thread
                    if (clientsList.ContainsKey(dataFromClient))
                    {
                        bytesFrom = System.Text.Encoding.ASCII.GetBytes("ERROR|" + dataFromClient + " That user name has been taken!|");
                        stream.Write(bytesFrom, 0, bytesFrom.Length);
                        stream.Flush(); // clear stream to make sure messages can't overlap
                        continue;
                    }

                    // Add the user's name and socket information to the clientList
                    clientsList.Add(dataFromClient, clientSocket);

                    // log the user on server side console
                    Console.WriteLine(dataFromClient + " joined chat room ");

                    // create a new handleClient then start the thread
                    handleClient client = new handleClient();
                    client.startClient(clientSocket, dataFromClient, clientsList, gList);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString()); // capture any errors that may occur and keeps server
                                                     // running in case of an error (hopefully)
                }
            }
        }