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

时间:2015-05-30 19:40:22

标签: c# sockets tcp

我构建了一个通过TCP套接字发送字符串的应用程序。它的工作原理如下:
服务器等待连接 - &gt;当有人连接时,如果字符串包含<EOG则读取字符串,它会停止,否则它会发送响应。 客户端的工作方式如下: 客户端尝试连接到服务器 - &gt;发送字符串 - &gt;从服务器读取响应,如果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>“那么回收方不会什么都可以 我如何让它发送整个消息然后才关闭?

1 个答案:

答案 0 :(得分:0)

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

希望这能以某种方式帮助某人:)