I tried to implement following class which should handle connecting to a server, as well as sending and receiving data.
Your feedback is welcome. Please note I am beginner in .NET and don't give too advanced feedback. I tested it and it seems to work. So in case you see some major problems please let me know, otherwise this class seems to fulfill my needs. I may add some small functionalities though.
Also can I better release resources than I am doing now? (maybe automatically close all resources I am using if that's possible?)
class DppTCPClient
{
public TcpClient m_client = new TcpClient();
public void Connect(string address, int port)
{
if (m_client.Connected)
throw new Exception("Connect: Already connected");
m_client.Connect(address, port);
}
public void WriteBytes(byte[] data, int length)
{
if (data.Length != length)
throw new Exception("WriteBytes: Length should be same");
// Get access to network stream
Stream stm = m_client.GetStream();
stm.Write(data, 0, data.Length);
}
public void ReadAllBytes(byte[] buffer, int length)
{
if (buffer.Length != length)
throw new Exception("ReadAllBytes: Length should be same");
Stream stm = m_client.GetStream();
// Start reading
int offset = 0;
int remaining = length;
while (remaining > 0)
{
int read = stm.Read(buffer, offset, remaining);
if (read <= 0)
throw new EndOfStreamException
(String.Format("ReadAllBytes: End of stream reached with {0} bytes left to read", remaining));
remaining -= read;
offset += read;
}
}
public void CloseDppClient()
{
if (m_client.Connected)
{
m_client.GetStream().Close();
m_client.Close();
}
}
}
ReadAllBytes
: Why do I need to provide the length if you can get it yourself? \$\endgroup\$