What are the limitations of WinSock2 sockets within threads?

by KeatonB   Last Updated June 30, 2020 00:05 AM - source

So I've run into some strange behavior on an application i'm developing in C using the windows API. Im trying to implement a closed connection server-client interface. However, for whatever reason connect() is failing consistently after between 1-50 successful iterations of the below sudo code: (WSA initialization is omitted, reasoning explained later, all that is important to know is TCP connection is used)

While(1) {
    if(failed) continue;
    connect(); //This fails repeatedly after several successful iterations
    if(failed) {

At this point, im likely going to just use an open connection as my program works when the connection is left open, and as often as data will be transferred, this is likely the better option anyways. However, for soon to be obvious reasons, I would like to know why the above doesnt work. The code that initializes WSA and the above code are called by a thread that my int WINAPI WinMain function creates. When the same code is executed within the normal int main() function in a previous developmental version (ie it is not being executed as a thread and not alongside WINAPI WinMain), it indefinitely connects and disconnects successfully to the same exact server (I.E. IT WORKS). Please let me know if there is a proper way to implement a closed connection. Why would the same code work in one instance and not another? Is it due to being executed within a thread? Is it due to being executed alongside WINAPI functions? I wouldn't think it is firewall related since it works in one instance.

Answers 1

Figured it out on my own, though I would like to clarify that based off of Microsoft documentation, my unrevised code should have worked in both circumstances (or not worked in both circumstances). I revised my code such that WSA cleanup is called after closesocket, and WSA initialization code was added to the beginning of the loop (ie WSA is initialized/created and destroyed with each iteration). I allowed the program to run for 4 hours today with no issues observed. I don't know if microsoft intended this behavior, but in my opinion something as logic-oriented as programming should never behave differently (all relevant variables held constant) in two different circumstances. Threads/other non-socket winapi functions shouldn't interfere with the operation of a socket, or at the very least such interactions should be explicitly documented. And if there are standards to abide by, under no circumstance should code that fails to adhere to such standards execute successfully.

January 31, 2020 23:16 PM

Related Questions

ZMQ 1-n queued vs multithreading

Updated February 12, 2017 14:02 PM