Search code examples
c#socketsclient-serverstreamwriter.net-4.5

How to get the stream from StreamSocket


I am developing Metro Client- Server application and in the client I use StreamSocket to connect to the listening server. Then I try to use a StreamWriter to send data to the Server. The problem is that when I am creating the new StreamWriter object I need to give him a stream argument. In my case I need to give him the Stream from the StreamSocket. Here is what I am talking about:

   private StreamWriter swSender;


   private StreamSocket tcpServer;

When attempting to send data:

   swSender = new StreamWriter(????);
   swSender.WriteLine(mytext);
   swSender.Flush();

???? must be the Stream from tcpServer, but there is not a GetStream() method like in TcpClient() class from the older framework. Any workarounds? Any ideas? Thank you in advance.


Solution

  • If i'm not mistake he have InputStream and OutputStream

    and then

    async private void WaitForData(StreamSocket socket)
    {
     var dr = new DataReader(socket.InputStream);
     //dr.InputStreamOptions = InputStreamOptions.Partial;
     var stringHeader = await dr.LoadAsync(4);
     if (stringHeader == 0)
     {
        // disconnected
        return;
     }
    
     int strLength = dr.ReadInt32();
     uint numStrBytes = await dr.LoadAsync((uint)strLength);
     string msg = dr.ReadString(numStrBytes);
     WaitForData(socket);
    }
    

    EDIT

    So you need something like this

    IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(text,   BinaryStringEncoding.Utf8);
    tcpServer.OutputStream.WriteAsync(buffer);