C# TcpListener ограничен локальной сетью или что-то не так с моим кодом? - PullRequest
1 голос
/ 20 февраля 2020

У меня проблема с приложением чата: оно не работает по сети. Я пробовал переадресацию портов и другие подобные методы. Я начинаю подвергать сомнению мой код. Я новичок в сети, поэтому, пожалуйста, помогите мне с этим. Я слышал о другом методе, использующем System.Net.Sockets, но я еще не пробовал это. Я слышал, что сокеты очень похожи на TcpListener, поэтому я не знаю, что сказать по этому поводу. Я убедился, что использовал правильный IP-адрес, AddressFamily.InterNetwork. Вот мой код:

static TcpListener server;

public static void ListenThread()
        {
            TcpClient client = null;
            NetworkStream stream = null;
            ClientConnection currentClientConnection = new ClientConnection();
            while (true)
            {
                if(client == null)
                {
                    client = server.AcceptTcpClient();
                    stream = client.GetStream();
                    currentClientConnection = new ClientConnection(client, stream);
                    clients.Add(currentClientConnection);
                    currentConnections++;

                    // Logging
                    string text = "A Client connection establieshed ! Connections : " + currentConnections;
                    Console.WriteLine(text);
                    Logger.WriteToLog(text);
                }           

                int bufferSize = client.ReceiveBufferSize;
                byte[] buffer = new byte[bufferSize];
                int i;
                string data = null;

                try
                {
                    while ((i = stream.Read(buffer, 0, bufferSize)) != 0)
                    {
                        data = Encoding.ASCII.GetString(buffer, 0, i);
                        data = ProcessData(data);

                        if (data == "/disconnect")
                        {
                            clients.Remove(currentClientConnection);
                            currentConnections--;

                            // Logging
                            string text = "A user left the server ! Connections : " + currentConnections;
                            Console.WriteLine(text);
                            Logger.WriteToLog(text);

                            SendToAllClients(string.Format("[Server]>> A user left the chat!"), client);
                            client.Close();
                            stream.Close();
                            client = null;
                            break;
                        }
                        else
                        {
                            SendToAllClients(data, client);
                        }
                    }
                }
                catch { };
            }
        }
        static void InitialiseServer()
        {
            Console.Write("Enter a port : ");
            serverPort = int.Parse(Console.ReadLine());
            Console.WriteLine();
            IPAddress localMachineIP = GetLocalIPAddress();
            try
            {
                Console.WriteLine("Initialising Server...");
                server = new TcpListener(localMachineIP,serverPort);
                Console.WriteLine("Server initialised !");
            }
            catch(Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                string text = string.Format("An error has occured while initalising server under IP={0} and port={1} . {2}", localMachineIP, serverPort, e.Message);
                Console.WriteLine(text);
                Logger.WriteToLog(text);
                Console.ForegroundColor = baseColor;
            }

            Console.Title = string.Format("Server initailised under {0}:{1}",localMachineIP.ToString(),serverPort);
        }

public static IPAddress GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip;
                }
            }

            return null;
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...