Convert Java Socket, BufferedReader, BufferedWriter to C#?

In Java we have Socket, BufferedReader and BufferedWriter, but what are the equivalent in C#?

Socket socket;
socket = new Socket(address, port);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

Answer

In C# you have Socket, StreamReader and StreamWriter classes. But you also have higher level classes that don’t require you to resort to sockets such as TcpListener and TcpClient. Here’s an example that connects to a listening socket and opens a stream reader that allows you to read from it:

using (var client = new TcpClient(address, port))
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream))
{
     // TODO: Read from the network stream
}

Leave a Reply

Your email address will not be published. Required fields are marked *