简体   繁体   中英

C# socket server doesn`t receive from client

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...

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM