NetworkStream.Write数据似乎没有到达接收套接字

时间:2016-09-18 20:05:29

标签: c# sockets tcp tcpclient networkstream

C#System.Net,Sockets

我遇到了一个问题,我无法弄清楚我可能做错了什么。

故事是,我将byte []应用程序数据从TcpClient套接字发送到另一个TcpClient套接字。这一切都很有效,直到我在发送应用程序数据之前添加自定义伪Athentication测试,之后发送和接收最初工作,失败。

我说失败了,但实际发生的事情是它只会在读取套接字上将3个字节全部设置为0。

Authenticate方法执行以下操作。 服务器端发送1字节数据(0-85),客户端接收它,将其视为int,将其乘以3并将一个字节发送回服务器。服务器检查该值,并将另一个字节返回设置为1。

所有这些看起来都运行正常,但是一旦认证后cliend发送的数据似乎没有收到,只有3个字节设置为0。

我希望套接字在程序的生命周期内保持打开状态,因此我无法处理该流,因为它也会处理套接字。

以下是客户端和服务器的完整代码,希望有人可能会看到我的错误,或者我错过了一个问题。

为了简洁起见,代码是故意不进行错误检查的,并且只是显示问题是非常基本的。

请注意,如果两个Authenticate方法都返回true,那么代码就会完全符合我的预期。

服务器。

class Program
    {
        static Random rnd = new Random(Guid.NewGuid().GetHashCode());
        static void Main(string[] args)
        {
            Process p = Process.Start(@"C:\Users\Teddy\Documents\visual studio 2015\code\Readissue\TheClient\bin\Debug\TheClient.exe");

            Console.Title = "Server";

            TcpListener lis = new TcpListener(
                new IPEndPoint(
                    IPAddress.Any, 4000
                    ));

            lis.Start();

            TcpClient cli = lis.AcceptTcpClient();
            NetworkStream ns = cli.GetStream();

            if (Authenticate(cli, ns))
            {
                Console.WriteLine("Good!");
                // This condition is met
            }
            else
            {
                Console.WriteLine("Bad!");
                Console.ReadLine();
                return;
            }

            // Wait until Carrier class of client
            // Sends data
            while (!ns.DataAvailable)
            {
                Thread.Sleep(100);
            }
            Console.WriteLine("DataAvailable");

            byte[] buffer = new byte[2048];
            //bytesread is always the value of 3.
            int bytesread = ns.Read(buffer, 0, buffer.Length);
            string sdata = Encoding.ASCII.GetString(buffer).Substring(0, bytesread);
            Console.WriteLine(sdata);
            Console.ReadLine();

            p.Kill();
            p.Close();

        }

        private static bool Authenticate(TcpClient cli, NetworkStream ns)
        {
            //return true;
            byte[] rcv = new byte[1];
            int isnd = rnd.Next(0, 85);
            byte[] snd = new byte[1] { (byte)isnd };

            //Sends a random number
            //and waits for response
            ns.Write(snd, 0, snd.Length);
            while (!ns.DataAvailable)
            {
                Thread.Sleep(10);
            }

            // Expects response to be 
            // random number x 3
            int br = ns.Read(rcv, 0, rcv.Length);
            int ircv = rcv[0];

            int iok;
            if (ircv == (isnd * 3))
            {
                // Confirm random number x 3
                iok = 1;
                byte[] bok = new byte[1] { (byte)iok };
                ns.Write(bok, 0, snd.Length);
                return true;
            }
            else
            {
                iok = 0;
                byte[] bok = new byte[1] { (byte)iok };
                ns.Write(bok, 0, snd.Length);
                return false;
            }
        }

        class Carrier
        {
            public double PointX { get; set; }
            public double PointY { get; set; }
            public string Comment { get; set; }

            public Carrier(byte[] bytes)
            {
                string[] tmpStrings = Encoding.ASCII.GetString(bytes)
                    .Split('|');

                PointX = Convert.ToDouble(tmpStrings[0]);
                PointY = Convert.ToDouble(tmpStrings[1]);
                Comment = tmpStrings[2];
            }
        }
    }

客户端

class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Client";

            IPEndPoint EP = new IPEndPoint(
                    IPAddress.Parse("192.168.1.100"), 4000
                    );

            TcpClient cli = new TcpClient();
            cli.Connect(EP);
            if (!cli.Connected)
            {
                Console.WriteLine("Not connected!");
                return;
            }
            Console.WriteLine("Connected!");
            NetworkStream ns = cli.GetStream();

            if (Authenticate(cli, ns))
            {
                Console.WriteLine("Good!");
                // This condition is met
            }
            else
            {
                Console.WriteLine("Bad!");
                return;
            }

            // Send data to server
            Carrier carrier = new Carrier();
            string stringtosend = carrier.ToString();
            byte[] bytestosend = Encoding.ASCII.GetBytes(stringtosend);
            ns.Write(bytestosend, 0, bytestosend.Length);

            Console.WriteLine("Data sent!");
            Console.ReadLine();

        }

        private static void UseClient(TcpClient cli, NetworkStream ns)
        {
            Console.WriteLine(ns.CanRead);
        }

        private static bool Authenticate(TcpClient client, NetworkStream ns)
        {
            //return true;
            byte[] rcv = new byte[1];
            while (!ns.DataAvailable)
            {
                Thread.Sleep(10);
            }

            int br = ns.Read(rcv, 0, rcv.Length);
            int ircv = rcv[0];
            int result = ircv * 3;
            byte[] snd = BitConverter.GetBytes(result);
            ns.Write(snd, 0, snd.Length);

            while (!ns.DataAvailable)
            {
                Thread.Sleep(10);
            }

            br = ns.Read(rcv, 0, rcv.Length);

            int iok = rcv[0];
            if (iok == 1)
            {
                return true;
            }
            return false;
        }
    }

    class Carrier
    {
        public double PointX { get; set; }
        public double PointY { get; set; }
        public string Comment { get; set; }


        public Carrier()
        {
            PointX = 1.00;
            PointY = 2.00;
            Comment = "A longer comment string";
        }

        public override string ToString()
        {
            return PointX.ToString() + "|"
                + PointY.ToString() + "|"
                + Comment;
        }
    }

1 个答案:

答案 0 :(得分:0)

因为我怀疑,问题出在客户端的Authenticate方法中。 我发送的是int而不是单个字节。令人讨厌的代码行是。

byte[] snd = BitConverter.GetBytes(result);

应该是哪一个。

byte[] snd = new byte[1] { (byte)result };

感谢jdweng发现错误。

PS,感谢你的兴趣低落选民,请接受我真诚的同情。