TCP Client Connection

2019-02-13 10:00发布

问题:

I have an application that I have written for my application distributed throughout the company to send data to me through our Windows 2003 server (running IIS 6.0). Small text messages get through, but larger messages containing more data (about 20 KB) are not getting through.

I set the byte buffer to the TCP Client’s buffer size. I noticed that my data was being received on the server; however, it only looped through the receive routine once, and my large files were always exactly the size of the buffer size, or 8 KB on our server. In other words, my code only makes it through one loop before the server closes the socket connection.

Thinking there might be an issue with filling the whole buffer, I tried limiting my read/writes to just 1 KB but this only resulted in our server closing the socket after receiving 1 KB before closing the connection.

I send the server’s error message back to the client so I can view it. The specific error message that I receive from the client is:

“Unable to write data to the transport connection: An established connection was aborted by the software in your host machine.”

I updated my server application so that the underlying TCP Socket would use “keep alives” with this line:

client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);

Now, whenever I attempt sending a message, the client receives the error:

“Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.”

Our Network Administrator has told me that he does not have a firewall or any ports blocked on our internal server.

Googling the errors, I found posts suggesting people try to telnet into the server. I used their directions to telnet into the server, but I am not sure what to make of the response:

C:> telnet Welcome to Microsoft Telnet Client

Escape Character is ‘CTRL+]’

Microsoft Telnet> open cpapp 500 Connecting To cpapp…

This is all I get. I never get an error, and Microsoft’s Telnet screen will eventually change to “Press any key to continue…” – I guess it times out, but my code is somehow able to connect.

I have tried other ports in code and through Telnet including 25, 80, and 8080. Telnet kicks out port 25, but my application seems to read the first loop no matter what port I tell it to run.

Here is my code that runs on the clients:

int sendUsingTcp(string location) {
  string result = string.Empty;
  try {
    using (FileStream fs = new FileStream(location, FileMode.Open, FileAccess.Read)) {
      using (TcpClient client = new TcpClient(GetHostIP, CpAppDatabase.ServerPortNumber)) {
        byte[] riteBuf = new byte[client.SendBufferSize];
        byte[] readBuf = new byte[client.ReceiveBufferSize];
        using (NetworkStream ns = client.GetStream()) {
          if ((ns.CanRead == true) && (ns.CanWrite == true)) {
            int len;
            string AOK = string.Empty;
            do {
              len = fs.Read(riteBuf, 0, riteBuf.Length);
              ns.Write(riteBuf, 0, len);
              int nsRsvp = ns.Read(readBuf, 0, readBuf.Length);
              AOK = Encoding.ASCII.GetString(readBuf, 0, nsRsvp);
            } while ((len == riteBuf.Length) && (-1 < AOK.IndexOf("AOK")));
            result = AOK;
            return 1;
          }
          return 0;
        }
      }
    }
  } catch (Exception err) {
    Logger.LogError("Send()", err);
    MessageBox.Show(err.Message, "Message Failed", MessageBoxButtons.OK, MessageBoxIcon.Hand, 0);
    return -1;
  }
}

Here is my code that runs on the server:

SvrForm.Server = new TcpListener(IPAddress.Any, CpAppDatabase.ServerPortNumber);

void Worker_Engine(object sender, DoWorkEventArgs e) {
  BackgroundWorker worker = sender as BackgroundWorker;
  string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Application.CompanyName);
  if (Directory.Exists(path) == false) Directory.CreateDirectory(path);
  Thread.Sleep(0);
  string eMsg = string.Empty;
  try {
    SvrForm.Server.Start();
    do {
      using (TcpClient client = SvrForm.Server.AcceptTcpClient()) { // waits until data is avaiable
        if (worker.CancellationPending == true) return;
        client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
        string location = Path.Combine(path, string.Format("Acp{0:yyyyMMddHHmmssff}.bin", DateTime.Now));
        byte[] buf = new byte[client.ReceiveBufferSize];
        try {
          using (NetworkStream ns = client.GetStream()) {
            if ((ns.CanRead == true) && (ns.CanWrite == true)) {
              try {
                int len;
                byte[] AOK = Encoding.ASCII.GetBytes("AOK");
                using (FileStream fs = new FileStream(location, FileMode.Create, FileAccess.Write)) {
                  do {
                    len = ns.Read(buf, 0, client.ReceiveBufferSize);
                    fs.Write(buf, 0, len);
                    ns.Write(AOK, 0, AOK.Length);
                  } while ((0 < len) && (ns.DataAvailable == true));
                }
                byte[] okBuf = Encoding.ASCII.GetBytes("Message Received on Server");
                ns.Write(okBuf, 0, okBuf.Length);
              } catch (Exception err) {
                Global.LogError("ServerForm.cs - Worker_Engine(DoWorkEvent)", err);
                byte[] errBuf = Encoding.ASCII.GetBytes(err.Message);
                ns.Write(errBuf, 0, errBuf.Length);
              }
            }
          }
        }
        worker.ReportProgress(1, location);
      }
    } while (worker.CancellationPending == false);
  } catch (SocketException) {
    // See MSDN: Windows Sockets V2 API Error Code Documentation for detailed description of error code
    e.Cancel = true;
  } catch (Exception err) {
    eMsg = "Worker General Error:\r\n" + err.Message;
    e.Cancel = true;
    e.Result = err;
  } finally {
    SvrForm.Server.Stop();
  }
}

Why doesn’t my application continue reading from the TCP Client? Have I neglected to set something that tells the Socket to stay open until I have finished? The server code never sees an exception because the TCP Client is never stopped, so I know there is no error.

Our Network Administrator has not received his Associates Degree yet, so if it turns out to be an issue with the Server, kindly be detailed in your description of how to resolve this, because we might not understand what you’re saying.

I apologize for this being so long, but I want to make sure you folks out there know what I'm doing - and maybe even gleam some information from my technique!

Thanks for helping! ~Joe

回答1:

You should precede the sent content with the length of that content. Your loop assumes that all of the data is sent before the loop executes, when in reality your loop is executing as the data is sent. There will be times when there is no data waiting on the wire, so the loop terminates; meanwhile, content is still being sent across the wire. That's why your loop is only running once.



回答2:

If I read your code correctly, you've basically got (sorry for the c-style - I'm not good with c#:

do
{
  socket = accept();
  read(socket, buffer);
}while(not_done);

If I'm correct, then it means you need... a little more in there. If you want it to be serialized, reading each upload in sequence, you'll want a second loop:

do
{
  socket = accept();
  do { read(socket, buffer); not_done_reading=...; } while (not_done_reading);
}while(not_done);

If you want to read multiple uploads simultaniously, you'll need something more like:

do
{
  socket = accept();
  if( !fork() )
  {
    do { read(socket, buffer); not_done_reading=...; } while (not_done_reading);
  }
}while(not_done);


回答3:

Your telnet example is somewhat contradictory to the behaviour of the code that you describe - if you are ever able to get anything on the server, the "telnet <hostname> <portnumber>" should get you to a blank screen pretty quickly (on windows machine in the CMD prompt that is). So, this is the first strange thing - best debugged with wireshark, though.

Code-wise, I think it may be problem with this inner line on the server:

... while ((0 < len) && (ns.DataAvailable == true));

You say that you want to loop while you were able to read something and while there is some data available.

However, it may be that the second segment has not made it to the server yet, so there is no data available yet, so you are falling out from this loop.

You should loop receiving data while you are reading something and while there has not been any read error - this guarantees that even on the slow links you will reliably receive the data.

A side note:

I notice your protocol is request-response-request-response type. It works well on the LAN, however if you need in the future to make it work over the high-round-trip-time links, this will become a big performance bottleneck (MS SMB protocol used for filetransfers or TFTP works in this fashion).

(Disclaimer: I didn't code in C# much, so might have been wrong in the interpretation of "DataAvailable()" method, take this FWIW).

Edit: probably my answer above would need to be corrected according to your protocol - i.e. you'd need to first read the length of the file, and then read the file - since if you take it verbatim it will break the way you designed it completely.

That said, with TCP one should never assume the number of write() operations on the sender side is the same as number of read() operations on the receiver side - in some cases it may be the case (no packet loss, no Nagle) - but in the general case it would not be true.



标签: c# tcp stream