开发者

get length of data sent over network to TCPlistener/networkstream vb.net

开发者 https://www.devze.com 2022-12-15 17:08 出处:网络
It seems the most obvious thing, but I just can\'t work out how to get the length of bytes sent over a network using a TCPClient and TCPListener?

It seems the most obvious thing, but I just can't work out how to get the length of bytes sent over a network using a TCPClient and TCPListener? This is my code so far:

   'Must listen on correct port- must be same as port client wants to connect on.
    Const portNumber As Integer = 9999
    Dim tcpListener As New TcpListener(IPAddress.Parse("192.168.2.7"), portNumber)

    tcpListener.Start()
    Console.WriteLine("Waiting for connection...")

    'Accept the pending client connection and return 
    'a TcpClient initialized for communication. 
    Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
    Console.WriteLine("Connection accepted.")
    ' Get the stream
    Dim networkStream As Netwo开发者_如何转开发rkStream = tcpClient.GetStream()
    '' Read the stream into a byte array

I need to get the length of the networkstream to set the size of the array of bytes I'm going to read the data into. But the networkStream.length is unsupported and does not work and throws an Notsupportedexception.

The only other way I can think of is to send the size of the data before sending the data, but this seems the long way round.


I realize this post is old but I feel there is an easier way to accomplish this task with TcpListener / TcpClient

You can use a BinaryFormatter to accomplish reading and writing from a NetworkStream where you don't know the exact length.

Using

System.Runtime.Serialization.Formatters.Binary;

Client Side

    string[] animals = { "Dog", "Cat", "Mouse" };
    TcpClient c = new TcpClient();
    c.Connect("YourServer", someport);
    using (NetworkStream ns = c.GetStream())
    {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ns, animals);
    }

Server Side

    string[] animals;
    TcpListener l = new TcpListener(IPAddress.Any, someport);
    l.Start();
    TcpClient c = l.AcceptTcpClient();
    using (NetworkStream ns = c.GetStream())
    {
            BinaryFormatter bf = new BinaryFormatter();
            animals = (string[])bs.Deserialize(ns);
    }

As long as you know the type that you're sending and receiving this a way to send and receive data across NetworkStreams without knowing the exact byte count.

If you're just sending a simple string across a NetworkStream however you could use a simple StreamWriter and the Write(String) method to write to the stream and a StreamReader and the ReadToEnd() method to retrieve your string at the other end.

Edit: I was just thinking about this answer the other day and I realize that it's important to note here that in order to use a BinaryFormatter the object must be able to be serialized by being marked with the SerializableAttribute, which is the case of some built-in types, makes this not an option. I apologize for the late edit but I felt this was important to note.


Not sure what object type you are expecting but this works and you could keep track of the final size, sorry in C# though:

System.Net.Sockets.NetworkStream nwStream = objTcp.GetStream();
System.IO.StreamReader stReader = new System.IO.StreamReader(nwStream);

string strTemp = ReadFromBuffer(stReader);

private string ReadFromBuffer(System.IO.StreamReader objReader)
{
        int intRead=1024;
        System.Text.StringBuilder stbBugger = new StringBuilder();
        char[] chrTempBuffer = new char[1024];

        while (intRead == 1024)
        {
            intRead = objReader.Read(chrTempBuffer, 0, 1024);
            stbBugger.Append(chrTempBuffer, 0, intRead);
        }

        return stbBugger.ToString();
    }

It all depends on what you are needing to read and what type of stream you use. The method here you could add a count to as well while reading the results if you really needed to.

Just keep track of the number of char's read during the operation and you have a size plus the data.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号