Problem in code C#

Asked

Viewed 58 times

1

Does anyone know what the problem is with this code below? The following error is occurring: "The stream is not writable"

     TcpListener tcpl = new TcpListener(500);
        tcpl.Start();
        Socket sock = tcpl.AcceptSocket();
        NetworkStream stream = new NetworkStream(sock);
        BinaryWriter write;


        while (true)
            {


            string Resp = string.Format("{0}\n{1}\n{2}",
                "HTTP/1.1 890 FOUND",
                "",
                "<h1>Worked!</h1>"
                );

            write = new BinaryWriter(stream);
            write.Write(Resp);
            write.Close();
            }
        tcpl.Stop();
        sock.Close();
        stream.Close();
  • When does it come out of the loop? And for what that loop?

  • The "never" loop exits, it is a "server" that receives connections continuously. It serves precisely to never stop receiving and answering connections.

  • ok.. but in that case use socket.Connected to verify.

1 answer

0

When you execute the command write.Close(); he closes the appeal NetworkStream stream and therefore cannot record. Try:

using (BinaryWriter writer = new BinaryWriter(stream))){
    writer.Write(Resp);
}

or

using (BinaryWriter writer = new BinaryWriter(stream, Encoding.Default, true))){
    writer.Write(Resp);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.