i make a simple TCP client/server in C# and i have the problem. When i test my code with telnet, the server is reading the socket fine and wrote the result. But when my client is writting a sentence on the socket, the server is block at the readLine function.
Here you have my client :
public Boolean initConnection(String ip)
{
try
{
this.client.Connect("127.0.0.1", 40000);
this.output = this.client.GetStream();
this.reader = new StreamReader(this.output, Encoding.UTF8);
this.writer = new StreamWriter(this.output, Encoding.UTF8);
writer.Write("one sentence");
return (true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return (false);
}
}
and here you have my server :
class SNetwork
{
private Thread Tread;
private TcpListener server;
private TcpClient client;
private StreamReader reader;
private StreamWriter writer;
private NetworkStream output;
private State state;
public void initReading()
{
this.server = new TcpListener(IPAddress.Any, 40000);
output = client.GetStream();
reader = new StreamReader(output, Encoding.UTF8);
writer = new StreamWriter(output, Encoding.UTF8);
this.Tread = new Thread(new ThreadStart(this.read)); // this.Tread is a thread
this.Tread.Start();
}
private void read()
{
try
{
while (Thread.CurrentThread.IsAlive)
{
String result;
if (this.client.Client.Poll(10, SelectMode.SelectRead))
{
this.state = State.Closed;
break;
}
else
{
result = reader.ReadLine();
if (result != null && result.Length > 0)
Console.WriteLine(result);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Anyone can help me plz ? i don’t find a solution
This code:
isn’t writing a line terminator – so your server code doesn’t know that you’ve finished the line. Change it to
WriteLine(and flush the writer) it should be okay.You always need to bear in mind that TCP/IP is a stream-based protocol – you can’t expect the server to receive the data with as many
Readcalls as you issuedWritecalls, and if you’re going for a line-terminated protocol on top, you need to make sure you terminate your lines.(As a separate matter, it would be a good idea to follow .NET naming conventions…)