2010-01-08 7 views
1

네트워크를 통해 전송되는 데이터의 길이를 얻는 것은 가장 분명한 것 같지만 TCPClient 및 TCPListener를 사용하여 네트워크를 통해 전송되는 바이트 길이를 얻는 방법을 알아낼 수 없습니까? 이 지금까지 내 코드입니다 : 내가으로 데이터를 읽을거야 바이트의 배열의 크기를 설정할 수는 NetworkStream의 길이를 얻을 필요가TCPListener/networkstream vb.net

'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 NetworkStream = tcpClient.GetStream() 
    '' Read the stream into a byte array 

. 그러나 networkStream.length는 지원되지 않으며 작동하지 않고 Notsupportedexception을 throw합니다.

내가 생각할 수있는 유일한 다른 방법은 데이터를 보내기 전에 데이터 크기를 보내는 것입니다. 그러나 이것은 먼 길을가는 것처럼 보입니다.

답변

1

확실하지 당신은 기대하고 있지만이 작동하고 있지만 C#으로 죄송 최종 크기의 트랙을 유지할 수있는 것을 객체 유형 :

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(); 
    } 

을 그것은 모두 당신이 어떤 종류의 읽기 및 필요 무엇에 따라 달라집니다 당신이 사용하는 스트림의. 이 방법을 사용하면 실제로 필요한 경우 결과를 읽는 동안 카운트를 추가 할 수 있습니다.

작업 중에 읽은 char 수를 추적하면 크기와 데이터가 더해집니다.

+0

최대 1024 바이트까지만 읽을 수 있습니까? 데이터를 가져 오기 전에 데이터의 크기가 필요하므로 읽을 바이트 수를 설정할 수 있습니다. –

+0

실제로는 한 번에 최대 1024 개를 읽습니다. 더 적 으면 읽기가 적어집니다. 그러므로 while 루프. read 명령은 실제로 읽은 바이트 수를 반환합니다.그러나 버퍼를 먼저 설정해야합니다. –

+0

예, 1024 바이트 이상인 경우 어떻게됩니까 ?? 그리고 데이터의 길이가 필요한 이유는 버퍼를 설정하는 것입니다 !!! –

4

이 게시물은 오래 실현하지만 당신은 당신이 모르는 곳에 NetworkStream에서 읽기 및 쓰기를 달성하기 위해 BinaryFormatter을 사용할 수 있습니다 TcpListener/TcpClient

으로이 작업을 수행하는 쉬운 방법이 느낌 정확한 길이. 사용

System.Runtime.Serialization.Formatters.Binary; 

클라이언트 측

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); 
    } 

만큼 당신이 t를 알고

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); 
    } 

서버 측 정확한 바이트 수를 몰라도 NetworkStreams를 통해 데이터를 보내고받는 방법을 보내고받는 중입니다. 당신은 당신이 다른 쪽 끝에서 당신의 문자열을 검색 할 스트림과 StreamReaderReadToEnd() 방법에 쓸 간단한 StreamWriterWrite(String) 방법을 사용할 수 있습니다 그러나 NetworkStream를 통해 간단한 문자열을 보내는 경우

.

편집 : 전날이 대답에 대해 생각하고 있었고 BinaryFormatter을 사용하려면 SerializableAttribute으로 표시하여 해당 객체를 직렬화 할 수 있어야한다는 것을 알아야합니다. 일부 기본 제공 유형의 경우이 옵션이 아닙니다. 나는 늦은 편집에 사과하지만 나는 이것이 중요하다고 느꼈다.