簡體   English   中英

服務器/客戶端未發送所有字節(TCP套接字)

[英]Server/Client not sending all the bytes (TCP Sockets)

我構建了一個通過TCP套接字發送字符串的應用程序。 它是這樣的:
服務器等待連接->當有人連接時,服務器將讀取字符串,如果字符串包含<EOG它將停止,否則它將發送響應。 客戶端的工作方式如下:嘗試連接到服務器的客戶端->發送字符串->從服務器讀取響應,如果respod包含<EOG>它將停止。
它發送我告訴它的每個字符串,但是當我發送包含<EOG>的字符串時,它僅發送5個字節並停止。 這是服務器代碼:

 static void Main(string[] args)
        {
            string messageFromClient = null;
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            byte[] bytes = new byte[1024];
            IPAddress ipAdress = IPAddress.Parse(LocalIPAddress());
            const int PORT = 13000;
            IPEndPoint localEndPoint = new IPEndPoint(ipAdress, PORT);
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);
                Console.WriteLine("Wating for a connection..");
                Socket handler = listener.Accept();
                Console.WriteLine("Got a connection from {0}", handler.RemoteEndPoint.ToString());
                while (true)
                {
                    while (true)
                    {

                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);
                        messageFromClient += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                        if (messageFromClient.IndexOf("<Stop>") > -1) break;
                    }
                    if (messageFromClient.Contains("<EOG>"))
                    {
                        Console.WriteLine("Text recived: {0}",messageFromClient.Replace("<Stop>",""));
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        Console.WriteLine("Handler closed.");
                        return;
                    }
                    Console.WriteLine("Text recived: {0}", messageFromClient.Replace("<Stop>", ""));
                    messageFromClient = null;
                    string readInput = Console.ReadLine() + "<Stop>";
                    byte[] messageToClient = Encoding.ASCII.GetBytes(readInput);
                    handler.Send(messageToClient);
                    if (readInput.Contains("<EOG>"))
                    {
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        Console.WriteLine("Handler closed.");
                        return;
                    }
                }
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.ToString());
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine(ane.ToString());
            }

        }
        public static string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }
            return localIP;
        }

這是客戶端代碼:

static void Main(string[] args)
        {
            IPAddress ipAdress = IPAddress.Parse(LocalIPAddress());
            byte[] bytes = new byte[1024];
            const int PORT = 13000;
            IPEndPoint remoteEP = new IPEndPoint(ipAdress, PORT);
            Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            string messageFromServer = null;
            try
            {
                sender.Connect(remoteEP);
                Console.WriteLine("Connected to {0}",sender.RemoteEndPoint.ToString());
                while (true)
                {
                    string readInput = Console.ReadLine() + "<Stop>";
                    byte[] messageToServer = Encoding.ASCII.GetBytes(readInput);
                    if (readInput.Contains("<EOG>"))
                    {
                        messageToServer = Encoding.ASCII.GetBytes("<EOG>");
                        int bytesSentEnd = sender.Send(messageToServer);
                        Console.WriteLine("Sent {0} bytes to the server", bytesSentEnd);
                        sender.Shutdown(SocketShutdown.Both);
                        sender.Close();
                        Console.WriteLine("Sender closed.");
                        return;
                    }
                    int bytesSent = sender.Send(messageToServer);
                    Console.WriteLine("Sent {0} bytes to the server", bytesSent);
                    while (true)
                    {
                        int bytesRec = sender.Receive(bytes);
                        messageFromServer += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                        if (messageFromServer.IndexOf("<Stop>") > -1) break;
                        if (messageFromServer.Contains("<EOG>"))
                        {
                            sender.Shutdown(SocketShutdown.Both);
                            sender.Close();
                            Console.WriteLine("Sender closed.");
                            return;
                        }
                    }
                    Console.WriteLine("Message from server: {0}", messageFromServer.Replace("<Stop>",""));
                    messageFromServer = null;
                }
            }
            catch (SocketException se)
            {
                Console.WriteLine("Sokcet Exception: {0}", se.ToString());
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("Argument Null Exception: {0}", ane.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unexpected excetption: {0}",ex.ToString());
            }
        }
        public static string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }
            return localIP;
        }

如果用戶輸入“ hi <EOG> ”之類的信息,它將僅發送5個字節並自行停止。 現在我不希望這種情況發生,我希望它發送整個消息,然后才停止。 同樣,如果消息包含“ <EOG> ”,則接收方不會接收任何內容。
我怎樣才能讓它發送整個消息,然后才關閉?

通過執行jdweng告訴我的內容,我可以解決此問題,並對代碼進行了一些調整。 如果有人需要,這是工作代碼:
服務器端:

static void Main(string[] args)
    {

        string messageFromClient = null;
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        byte[] bytes = new byte[1024];
        IPAddress ipAdress = IPAddress.Parse(LocalIPAddress());
        const int PORT = 13000;
        IPEndPoint localEndPoint = new IPEndPoint(ipAdress, PORT);
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);
            Console.WriteLine("Wating for a connection..");
            Socket handler = listener.Accept();
            Console.WriteLine("Got a connection from {0}", handler.RemoteEndPoint.ToString());
            while (true)
            {
                while (true)
                {

                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    messageFromClient += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    if (messageFromClient.IndexOf("<Stop>") > -1) break;
                }
                if (messageFromClient.Contains("<EOG>"))
                {
                    Console.WriteLine("Text recived: {0}", messageFromClient.Replace("<Stop>", ""));
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                    Console.WriteLine("Handler closed.");
                    return;
                }
                Console.WriteLine("Text recived: {0}", messageFromClient.Replace("<Stop>", ""));
                messageFromClient = null;
                string readInput = Console.ReadLine() + "<Stop>";
                byte[] messageToClient = Encoding.ASCII.GetBytes(readInput);
                handler.Send(messageToClient);
                if (readInput.Contains("<EOG>"))
                {
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                    Console.WriteLine("Handler closed.");
                    return;
                }
            }
        }
        catch (SocketException se)
        {
            Console.WriteLine(se.ToString());
        }
        catch (ArgumentNullException ane)
        {
            Console.WriteLine(ane.ToString());
        }

    }
    public static string LocalIPAddress()
    {
        IPHostEntry host;
        string localIP = "";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                localIP = ip.ToString();
                break;
            }
        }
        return localIP;
    }

客戶端:

static void Main(string[] args)
    {
        IPAddress ipAdress = IPAddress.Parse(LocalIPAddress());
        byte[] bytes = new byte[1024];
        const int PORT = 13000;
        IPEndPoint remoteEP = new IPEndPoint(ipAdress, PORT);
        Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        string messageFromServer = null;
        try
        {
            sender.Connect(remoteEP);
            Console.WriteLine("Connected to {0}", sender.RemoteEndPoint.ToString());
            while (true)
            {
                string readInput = Console.ReadLine() + "<Stop>";
                byte[] messageToServer = Encoding.ASCII.GetBytes(readInput);
                if (readInput.Contains("<EOG>"))
                {
                    int bytesSentEnd = sender.Send(messageToServer);
                    Console.WriteLine("Sent {0} bytes to the server", bytesSentEnd);
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                    Console.WriteLine("Sender closed.");
                    return;
                }
                int bytesSent = sender.Send(messageToServer);
                Console.WriteLine("Sent {0} bytes to the server", bytesSent);
                while (true)
                {
                    int bytesRec = sender.Receive(bytes);
                    messageFromServer += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    if (messageFromServer.Contains("<EOG>"))
                    {
                        sender.Shutdown(SocketShutdown.Both);
                        sender.Close();
                        Console.WriteLine("Sender closed.");
                        return;
                    }
                    if (messageFromServer.IndexOf("<Stop>") > -1) break;
                }
                Console.WriteLine("Message from server: {0}", messageFromServer.Replace("<Stop>", ""));
                messageFromServer = null;
            }
        }

        catch (SocketException se)
        {
            Console.WriteLine("Sokcet Exception: {0}", se.ToString());
        }
        catch (ArgumentNullException ane)
        {
            Console.WriteLine("Argument Null Exception: {0}", ane.ToString());
        }
        catch (Exception ex)
        {
            Console.WriteLine("Unexpected excetption: {0}", ex.ToString());
        }
    }
    public static string LocalIPAddress()
    {
        IPHostEntry host;
        string localIP = "";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                localIP = ip.ToString();
                break;
            }
        }
        return localIP;
    }

希望這可以以某種方式幫助某人:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM