Socket programming question

  • Thread starter Thread starter sebastian.harko
  • Start date Start date
S

sebastian.harko

Hello,
I have a question related to socket programming.
I have this code:

TcpClient client = new TcpClient(hostName, port);

try
{
Stream s = client.GetStream();
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);
sw.AutoFlush = true;
sw.Write(message);
string result = sr.ReadLine();
Console.Write(result);
sw.Close();
sr.Close();
s.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine("Error.");
}


And the thing is that it doesn't work ...
 
You didn't mention ^how^ it didn't work. What were your expectations,
and how were they not met?

A few things to point out, you should really be using the using
statement for things that implement IDisposable (the Stream, StreamReader,
etc, etc).

Additionally, I believe the StreamReader performs some buffering. If
so, then it's possible that it is trying to read bytes that haven't been
sent on the stream yet.
 
Sorry ... it was an incomplete message.. I removed it and posted a new
message ....

You didn't mention ^how^ it didn't work. What were your expectations,
and how were they not met?

A few things to point out, you should really be using the using
statement for things that implement IDisposable (the Stream, StreamReader,
etc, etc).

Additionally, I believe the StreamReader performs some buffering. If
so, then it's possible that it is trying to read bytes that haven't been
sent on the stream yet.

--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)


Hello,
I have a question related to socket programming.
I have this code:
TcpClient client = new TcpClient(hostName, port);
try
{
Stream s = client.GetStream();
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);
sw.AutoFlush = true;
sw.Write(message);
string result = sr.ReadLine();
Console.Write(result);
sw.Close();
sr.Close();
s.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine("Error.");
}
And the thing is that it doesn't work ...
 
Back
Top