1
votes

I have an odd question. I am trying to write a C# server - client project using sockets for communication. I am new to C# but I have written the same project in Java and it worked just fine there.

So, the client connects to the server, creates the read/write streams from the socket's network stream and sends a single string through it but the server doesn't receive anything.

I am sure the server works fine because I have connected a Java client to it and it receives the string from client.

I don't understand how come the socket connects but nothing goes through it.

Here's the client's code:

...
socket = new TcpClient("localhost", PORT);
NetworkStream ns = socket.GetStream();
StreamReader rin = new StreamReader(ns);
StreamWriter wout = new StreamWriter(ns);
Console.WriteLine("-->Connected to server");
string msg;
for (; ; )
{
    Console.WriteLine("waiting to write");
    while(user.Equals("")) //user is set in Form thread working in parallel 
        System.Threading.Thread.Sleep(100);
    Console.WriteLine("sending: " + user);
    wout.WriteLine(user);
    wout.Flush();
    Console.WriteLine("SENT");
    ...

The PORT is the same, no exceptions are thrown (I have a try - catch around this), the client sends the string through the StreamWriter because it prints out "SENT" but the server waits at the receiving end (streamReader.ReadLine()) and nothing happens...

1
Don't use the backtick ` for apostrophes. That confuses the editor into thinking you are entering code snippets. Thanks :-) - mellamokb
Everything looks good. Are you seeing "Sent" wrote into the console after the write is executed? - Will
It might be helpful to have the server code since that seems to be the problem. - Rex Morgan
@Liviu Two things: 1) Accept some of your answers, and 2) Did you make sure the Firewall/Antivirus isn't blocking it? Try disabling it and let us know. - Oscar Mederos
1. Sorry for the backticks. 2. Yes, the "SENT" message is written on the console after write is executed. 3. The server works perfectly fine with the java client that sends the same string as the c# client, so that cannot be a problem. 4. Yes, the firewall/antivirus allows network communication - Liviu

1 Answers

0
votes

Try this:

socket = new TcpClient();
socket.Connect("localhost", PORT);
//... Your code continues here