如何确保Networkstream在返回C#

时间:2018-09-03 06:27:16

标签: c# sockets byte networkstream

我目前正在从事一项与NASA JPL通信以获取有关太阳系数据的副项目。对于与网络相关的任何事物来说,这都是全新的,并且在理解如何正确读取网络流方面存在一些问题。

这段代码是我能够拼凑的,在技术上可以正常工作,但是它并不是很可靠。问题在于,如果您经常发送命令,我经常无法读取响应,而在ping网络较高的情况下,似乎根本无法获得任何响应。

我已经尝试通过研究beginread或asyncread来解决此问题,但这确实超出了我的知识水平。

我意识到我需要做的是让代码在实际读取所有内容然后返回收到的消息之前等待响应。如果有人可以帮助我,那将不胜感激:)

 public void ServerSocket(string ip, int port)
    {
        try
        {
            client = new TcpClient(ip, port);
            Console.WriteLine("Connected to server.");
            today = DateTime.Now;
            tomorrow = today.AddDays(1);
        }
        catch (SocketException)
        {
            Console.WriteLine("Failed to connect to server");
            return;
        }

        //Assign networkstream
        networkStream = client.GetStream();

        //start socket read/write thread
        readWriteThread = new Thread(readWrite);
        readWriteThread.Start();

    }

    private void readWrite()
    {
        string command, recieved;
        bool title = false;

        //Read first thing given
        recieved = JplRead();
        Console.WriteLine(recieved);

        //Set up connection loop
        while (true)
        {
            Console.Write("Response: ");
            command = Console.ReadLine();


            if (command == "exit")
                break;

            JplWrite(command);
            Thread.Sleep(500);
            recieved = JplRead();

            Console.WriteLine(recieved);
        }

        Console.WriteLine("Disconnected from server");
        networkStream.Close();
        client.Close();
    }


    /// <summary>
    /// Converts message string into bytes and then sends them to JPL
    /// </summary>
    /// <param name="message"></param>
    public void JplWrite(string message)
    {
        message += Environment.NewLine;
        byte[] messageBytes = Encoding.ASCII.GetBytes(message);
        networkStream.Write(messageBytes, 0, messageBytes.Length);
        networkStream.Flush();
    }

    /// <summary>
    /// Reads network stream, has a buffer of 1024 bytes but reads all data through networkStream.DataAvailable
    /// </summary>
    /// <returns></returns>
    public string JplRead()
    {
        byte[] data= new byte[1024];
        StringBuilder recieved = new StringBuilder();

        int numberOfBytesRead = 0;

        // Incoming message may be larger than the buffer size, therefore reads all available data through this loop before stitching it togheter. 
        do
        {
            numberOfBytesRead = networkStream.Read(data, 0, data.Length);
            recieved.AppendFormat("{0}", Encoding.ASCII.GetString(data, 0, numberOfBytesRead));
        }
        while (networkStream.DataAvailable);

        return recieved.ToString();
    }
}

0 个答案:

没有答案