• 0

Help with TCP Socket Server Client


Question

Hi,

 

I am trying to write this TCP Socket Client Server app for testing purposes. It works for the most part but some things are not working and I need some help. Please see the project attached created in VS2013 targeting .NET Framework 4.5 using C#.

 

ServerClient.zip

 

I took the socket code from here https://code.msdn.microsoft.com/High-Performance-NET-69c2df2f

 

The issues I am having are,

 

* When I stop listening on server, I am still receiving data. I would expect that the client should find that it is not connected anymore and throw an error and disconnect.

* I need to send server time back to the client upon receiving data (once the receive is complete). I am doing that but it is not working.

* I have set the buffer size to 64 bytes but if I send more data then it doesn't like that. I thought it was possible to grab data to fill that buffer and then continue receiving more until it finishes.

* One last thing might I ask is some suggestions with error handling since the socket code from MSDN says the "LastError" is not the correct way of doing this.

 

So I am way over my head with TCP stuff because I don't do network programming often and need some help to sort of these issues.

 

Cheers :)

Link to comment
https://www.neowin.net/forum/topic/1257794-help-with-tcp-socket-server-client/
Share on other sites

2 answers to this question

Recommended Posts

  • 0
  On 26/05/2015 at 05:34, wrack said:

* When I stop listening on server, I am still receiving data. I would expect that the client should find that it is not connected anymore and throw an error and disconnect.

From a cursory glance, it doesn't appear to close accepted sockets in Stop().

public void Stop()
{
ConnectionSocket.Close();
_limitClientConnectionMutex.ReleaseMutex();
}
I don't know C# or .Net sockets very well, but isn't ConnectionSocket merely the listening socket? Calling this function won't actually close/inform the client that you disconnected. In C, I'd usually iterate through the client connections and gracefully shut them down:

for ( iter = list_first ( clients ); NULL != iter; iter = list_next ( clients, iter ) ) {
Socket *s = list_get_ptr ( iter );
shutdown ( s->fd, SHUT_RDWR );
close ( s->fd );
}
list_free ( clients );
  On 26/05/2015 at 05:34, wrack said:

* I need to send server time back to the client upon receiving data (once the receive is complete). I am doing that but it is not working.

I'd suggest you debug ProcessData() in the SocketUserToken class. You appear to be setting the non-blocking write buffer for the socket there:

var sendBuffer = Encoding.UTF8.GetBytes(received + " Time : " + DateTime.UtcNow.ToString("O")); // "O" = ISO-8601
args.SetBuffer(sendBuffer, 0, sendBuffer.Length);
You need to confirm this gets executed and does what it's supposed to do before you close the socket. I'm assuming the underlying class automatically sends the buffer once there's data there. If not, you may have to call some kind of send() function.

 

  On 26/05/2015 at 05:34, wrack said:

* I have set the buffer size to 64 bytes but if I send more data then it doesn't like that. I thought it was possible to grab data to fill that buffer and then continue receiving more until it finishes.

I think the problem is that you're limiting your packet/message buffer '_stringBuilder' in SocketUserTokenClass to DefaultBufferSize (64 bytes) as well. Specifically in SocketServerClass's ProcessAcept():

readSocket.UserToken = new SocketUserTokenClass(AddToLoggerMethod, acceptSocket, DefaultBufferSize);
Which translates to this executing:

if ((_totalByteCount + bytecount) > _stringBuilder.Capacity)
{
LastError = "Receive Buffer cannot hold the entire message for this connection.";
return false;
}
'_stringBuilder' is set to 64 by your DefaultBufferSize, so if you send any more than that it will error out. To be honest, I think SocketUserTokenClass is just a placeholder for your own custom receive/parsing packet functions. It's very rudimentary. However, provided you change the packet/message buffer size passed into the SocketUserTokenClass constructor, you should be fine. You need to understand that there are actually two buffers involved here. 1) The socket read buffer, and 2) The packet/message buffer. That's how most reliable network code works. You construct the packet/message once you've received the whole thing. That's usually done via encoding such as prefixing the packet size.

 

  On 26/05/2015 at 05:34, wrack said:

* One last thing might I ask is some suggestions with error handling since the socket code from MSDN says the "LastError" is not the correct way of doing this.

Sounds a lot like 'errno' from ISO C. There are only really two ways to handle errors:

1) Check return value from a function. Sometimes this is used in conjunction with 'errno' to determine the real error. For instance, the socket() function returns -1 if an error occurred. To obtain the actual error, you can access errno/call strerror().

2) Employ try/catch exception handling. Though in the case of sockets, it might not be efficient. After all, network errors are so common. I suppose it depends on how often you expect them to occur and whether you're willing to accept the performance penalty.

 

  On 26/05/2015 at 05:34, wrack said:

So I am way over my head with TCP stuff because I don't do network programming often and need some help to sort of these issues.

Networking is simple once you get the hang of it. You'll be writing your own packet protocols in no time ;)
This topic is now closed to further replies.
  • Posts

    • Fan Control V230 by Razvan Serea Fan Control is a powerful and versatile portable utility that allows you to monitor, control and customize the fans of your GPU and CPU to keep your machine cool and running smoothly. Fan Control supports a wide range of devices and hardware configurations, giving you complete control over your computer's cooling system. Fan Control backend is mainly based on LibreHardwareMonitor, an open source fork of the original OpenHardwareMonitor. This means that hardware compatiblity is entirely open for anyone to contribute, and doesn't rely on a single developer who may stop caring at some point. Combined with the plugin system, Fan Control is unlocked for many generations of hardware to come. Main features Guided setup process on first launch Save, edit and load multiple profiles Change the theme and color of the application. Multiple temperature sources ( CPU, GPU, motherboard, hard drives... ) Multiple fan curve functions, including a custom graph Mix fan curves or sensor togethers (max, min, average) Low resource usage Advanced tuning with steps, start %, stop %, response time and hysteresis FanControl V230 changelog: Update LibreHardwareMonitorLib (ITE IT8696E lost controls) Update translations Download: FanControl V229 | Installer ~15.0 MB (Open Source) View: Fan Control Homepage | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • "Conflicts of interest", says the man that put Elon Musk, Mr. Conflict of Interest #1 Himself, in charge of a government agency supervising his own contracts.
    • With our Labor unions, a snowball's chance in hell has more probability.
  • Recent Achievements

    • First Post
      EzraNougat earned a badge
      First Post
    • One Month Later
      westDvina earned a badge
      One Month Later
    • Community Regular
      Bern@rd went up a rank
      Community Regular
    • Week One Done
      Joey Solo earned a badge
      Week One Done
    • Week One Done
      Vicente C Alves earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      711
    2. 2
      +FloatingFatMan
      200
    3. 3
      ATLien_0
      163
    4. 4
      Xenon
      130
    5. 5
      wakjak
      110
  • Tell a friend

    Love Neowin? Tell a friend!