服务器/客户端没有发送所有字节(TCP套接字)

本文关键字:字节 TCP 套接字 客户端 服务器 | 更新日期: 2023-09-27 17:51:22

我构建了一个通过TCP套接字发送字符串的应用程序。它是这样工作的:
服务器等待连接->当有人连接时,它读取字符串,如果字符串包含<EOG,它停止,否则它发送响应。客户端是这样工作的:客户端试图连接到服务器->发送字符串->从服务器读取响应,如果响应包含<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;
        }

如果用户输入类似"嗨,<EOG>"它只发送5个字节,然后自动停止。现在我不希望这种情况发生,我希望它能发送完整的信息,然后自己停止。此外,如果消息包含"<EOG>",则接收方不会接收任何内容。
我怎样才能让它发送完整的信息,然后才关闭?

服务器/客户端没有发送所有字节(TCP套接字)

我能够通过做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;
    }

希望这对某人有所帮助:)