Question

Socket Error 10057 - Socket not connected when running within a thread

Asked by: steve-west

I'm developing a multi threaded application, with each thread using a socket connection to talk to the database.

The Socket component is based upon overbyte's ICS Wsocket, which is a essentially a non-blocking socket.

Anyway, the application services database requests. It has a maximum of, say 30 threads running at the same time. As a request is received, it is queued. When the number of threads falls below the threshold, requests are taken from the queue and threads created to service them. When a thread completes a request, it terminates.

This may work perfectly for a 1000 requests or sometimes 10.  The point is, occasionally I'm getting the old 10057 error - socket not connected error, as the request is sent though to the database.

This is puzzling. The SendStr is only called after the OnSessionConnected event so as far as I'm aware, socket is connected, but obviously me and the socket have differing opinions on this.

Also, the randomness of this is concerning me and so far, I've not been able to do anything to resolve it.

Any help would be greatly appreciated.

Thanks

Steve

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-03-03 at 02:32:22ID23208915
Tags

Borland Delphi 2006

Topics

Pascal Programming Language

,

TCP/IP

Participating Experts
1
Points
500
Comments
17

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Threading/queuing problem
    Hello, I am currently working with several classes (Threads) that process incoming data and give it to the next thread for further processing. Each thread has a queue from which it reads. This is the coding framwork I use for exchanging these objects: public class ThreadedO...
  2. threaded socket communication 1000 pts.
    Hello all, I am writing an component that allows me to connect to a server... (text based) I tried to make the component threadded... 1 thread owns the socket component and checks for in or outbound data and sends it.. the second thread reads the input buffer and generates ...
  3. Sockets + Threads
    I am working with sockets in java for the first time. Currently I have a thread linked to another thread using a socket. class x entends thread { private Socket y y = new Socket("xxx.xxx.xxx.xxx", 8000) } class y extends thread { private Socket x x = serverSoc...
  4. Thread threshold on JVM
    Hello all, Please I have the following questions: 1. What is the maximum number of threads a Java Virtual Machine (JVM) can accommodate at a time? 2. What happens when this threshold is reached? 3. Does the size of the heap available to JVM proportionate to the size of the...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ciulyPosted on 2008-03-03 at 07:07:11ID: 21032124

I'm curious how you are threading the ICS components. because them beeing non-blocking and relying on events, the events are fired in the calling threads context so you might need to synchronize access to some resources.
and since the error is random, it could be just because of that: badly or not sycnhronized access to a commonly used resource.

 

by: steve-westPosted on 2008-03-03 at 07:22:39ID: 21032297

A database server request thread is inherited from TThread. Each one creates a socket component that it uses to communicate with the database.

This has worked well in various other threaded applications I've written, it's just now I'm running into problems. This may be because the general activity of this application is much greater (although socket activity per thread is much less), though I'm not sure.

I would have thought if this was some kind of synchronisation issue, it wouldn't have worked at all.

What I have found is that after X (random amount but usually more than 10), the socket state changes from wsConnected to wsConnecting. It appears that because the database requests are serviced so quickly Winsock is somehow becoming flooded(?) and the WSAGetLastError returns WSAEWOULDBLOCK. This is then manifesting itself at the time of SenddStr (since the state is obviously not wsConnected).

At the time of SendStr, if the state is wsConnecting I've tried waiting around a bit (calling the ProcessMessages of the Socket object) to only proceed if it becomes connected.
The above results in the application flying through the first few batches of requests and then freezing for ages and then proceeding very slowly.

Really not sure I've fixed it. Is there a better solution to the one that I've come up with?

Thanks

Steve


 

by: ciulyPosted on 2008-03-03 at 07:49:39ID: 21032589

>> I would have thought if this was some kind of synchronisation issue, it wouldn't have worked at all.

that is not true, as synchronization problkems appear only when 2 or more threads try to simpultaneusly access one recourse. in you case, the chances of that could be 1% or 5% or something like that and this will look like randomness.

>> Really not sure I've fixed it. Is there a better solution to the one that I've come up with?

I'll need to understand a little the flow. is my understanding correct in that you are creating threads very fast and the connections are finishing very quickly?
if so, then why no use a thread pool and a conection pool? that way you can keep the connections open and re-use them (you will need a small amount of synchronization here twhen getting an open connection.
would that "fly" with your application?

 

by: steve-westPosted on 2008-03-03 at 08:25:48ID: 21033016

I have a managing object that has the threads running in a private list. It has a separate list of pending requests and as a thread terminates, a pending request is taken from the queue and a thread created to execute it.
All this happens very quickly. Between thread creation and disposal is there maybe 1 second max.  But this process is being repeated potentially 10s thousands of times.

I had considered maintaining  a set of constantly open connections but, the Socket component is a derived version of the ICS one. Default Socketty-type behaviour hasn't been modified, but there is quite a complex initialisation process which the socket undergoes when first created which places the database in to some kind of default state which is not changed easily. Altering of the Delphi code isn't the issue, it's the database side of things which I don't even want to go near for risk of inducing error into our other applications which do not need to keep resetting the database. (we're using a MUMPS database, not SQL etc, so database handling is unique to say the least)

Regarding the threads, they absolutely do not access any outside resource. There's obviously no  interface, a simple notification synchronisation method (which does access a COM object, but I can't see this as being an issue - it is within the synchronisation stage anyway). The threads simply issue a command on the database, wait for a result and place this in a list and then terminate.

 

by: ciulyPosted on 2008-03-03 at 08:51:05ID: 21033291

I know from experience that creating and destroying things fast and many times is bad to say the least.

what you have there is a manager, not a pool. you need a pool. basically, you need to modify the thread os that i gets to do oprations an dnot just one operation.
you have 2 options here:
- the manager adds jobs to the thread, which keeps a list of jobs and if no jobs present sleeps for 500 ms or 1 second or something like that.
- you keep the queue as it is and every thread troes to get one job from the queue and again, if the queue is empty, it sleeps for a while.

this will ease up the load on windows (because creating and destroying a thread also takes time).

next, connection pool. once the thread is create and teh socket is created, you only need to use it. so issue a command, get results, place results wherever you place them and start over over again.
there is one aspect which is not clear to me:
- the DB is beeing put in that default state every single time a soket is created and then taken out of that state every time the socket closes?
- if the DB is placed into that state only once and then for a looong while (or foreveer) it remains in that state, why is it a problem in creating the connection pool?

the only porblem you will need to take into account is while the thread runs, what are the chances of the DB getting out of that default state in which it was placed by the socket creation? if there are chances, then you will need to check before every job if the db is in the right state and place it in if not. but stil, it is a lot better (optimal) than recreating teh socket every time. that also takes time and windows resources.
I don't think you want to depend on the performance of windows layers for your application. if windows cannot create but 100 sockets per minute and that is not enough you're in deep trouble.

so lets break up the problem into smaller problems:
- thread pooling is easy. you create 30 threads at once and then all of them work. this is the simplest way. you can also create the threads only as needed, but that can be a little complicated, so I would leave it to when you have more free time
- connection pooling. this could be tricky since it depends on the DB. but it si possible.

so, is soemthinglike the attached pseud-code feasable for you?

mythread=class(tthread)
fconnection:tdbconnection;
protected
  procedure execute; override;
public
  constructor createl
  destructor destroy; override;
end;
 
procedure execute;
begin
  while not temrinated do
  try
    job:=getjob;// getjob gets a job from the queue 9shynchronized, of course)
    if job=nil then sleep(1000)
    else
      process(job);
  except
    / notify logger of error and log it to file
  end;
end;
 
constructor create;
begin
  create fdbconnection;
  inherited create(false);
end;
 
destructor destroy;
begin
  destroy db connection
end'
 
processjob will use dbconnection to send the command and retrieve the results.

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:

Select allOpen in new window

 

by: steve-westPosted on 2008-03-03 at 09:03:47ID: 21033455

Thanks for this.

In the other threaded applications, the lifetime of a thread was much longer.

In the case of this application , it does make sense to re-use the thread objects, but this is not going to be five minutes work.

I'll get back to you to let you know if it improves things...

Thanks

Steve

 

by: ciulyPosted on 2008-03-03 at 09:11:13ID: 21033555

take your time

 

by: steve-westPosted on 2008-03-04 at 05:56:00ID: 21040886

Hi Ciuly

Finished the implementation of the connection pool, but unfortunately it's made no difference. I'm still getting bucket loads of 10057 errors.

The sockets connect OK but at some stage, the WSAGetLastError indicates that the socket becomes blocked and the state changes to wsConnecting. Therefore when the socket tries to write, 10057 is the result. Is this indicative of Winsock not completing the last operation and therefore blocking the non-blocking socket?

To make matters worse, I'm also occasionally getting (not nearly as often as the 10057) the error "Socket already in-use". I've only ever come across this before when writing socket based service applications and have learnt to live with the error has being a result of running within a service, but are the two issues related?


Thanks

Steve

 

by: ciulyPosted on 2008-03-04 at 06:12:55ID: 21041045

well, now that you are using thread pooling, you should not get the socket already in use error since one socket is only created once and used multiple times. if you do get it, then you probably missed some initialization code somewhere.

now, since you are using pooling, one thing should be clear:
- if the socket gets disconnected, all jobs on that thread will throw 10057.

are you seeing this behaviour? if so, do a search in your code and check if you somewhere disconnect the socket yourself. if you can't find anything like that, then try to follow the flow of the execution of a job and isolate the places where the socket could get disconnected: for example the server (DB) could disconnect the socket in some circumstances. if this is true, then before each job you will have to chheck if ythe socket is connected or not, and connect it if it's not.
(this sould also be a workaround, since if I am not wrong, you will only do one connection per job, so if the current job disconnects the socket, it will be reconnected when the next job is processed)

if you don't see that behaviour, then there is something you're not telling me or you didn't do as I instructed. because in a thread-connection setup as I explained a few days earlier, once the socket gets disconnected it will stay disconnected andal requests will throw errors.

 

by: steve-westPosted on 2008-03-04 at 06:28:29ID: 21041208

From what I can see, the 10057 is nothing to do with the socket disconnecting - it hasn't, only its STATE changed (it doesn't fire the OnSessionDisconnect or close events). These are the lines taken from the components (OverbyteICSWsocket),. at the end of the Connect method

        iStatus := WSocket_Synchronized_connect(FHSocket, TSockAddr(sin), sizeof(sin));
        if iStatus = 0 then
            ChangeState(wsConnecting)
        else begin
            iStatus := WSocket_Synchronized_WSAGetLastError;
            if iStatus = WSAEWOULDBLOCK then
                ChangeState(wsConnecting)

iStatus is coming through as WSAEWOULDBLOCK , therefore changing the state from wsConnected to wsConnecting. At the "iStatus=....." line, the socket's state is wsConnected.

There is only one socket per thread, so closing a socket in one thread - or getting the 10057 error - shouldn't affect any others. However, once one thread has the error, the others quickly report it afterwards. I think this is a symptomatic of an underlying cause, and not a result of inter-thread behaviour.

BTW, The sockets always check that they are connected before sending anything and connect if necessary..

To start with the application works fine for a while - reusing the threads as I expect. Only after a minute or so do the first errors pop-up.

Don't know what else to try.

Regards

Steve

 

by: ciulyPosted on 2008-03-04 at 06:48:35ID: 21041424

well, I usually do this first, but better late than never. so I checked MSDN:
"WSAEWOULDBLOCK
10035
Resource temporarily unavailable.

This error is returned from operations on nonblocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket. It is a nonfatal error, and the operation should be retried later. It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK_STREAM socket, since some time must elapse for the connection to be established."

but I am looking at what you are showing to me and it makes no sense. because I said thta you create the socket once. so you should have as many sockets as threads and not one more or less. and if they are all created and they are all connected, how can you get WSAEWOULDBLOCK since you are not connecting anymore?

did you do as I said and reuse the connection? if so, what am I missing?

 

by: steve-westPosted on 2008-03-04 at 07:16:29ID: 21041719

I read that article as well before making the post.

There is only every one socket per thread. The socket is only told (by me ) to connect the once.

What appears to be happening is that during the socket's lifetime, its connected status changes from wsConnected to wsConnecting, perhaps multiple times. From other articles I've read the status change is a a result of Winsock being asked to do something, yet is busy and as  a result of the socket being a non-blocking  socket, indicates to the socket...

 "if you were a blocking socket, I would have blocked you, but since you're not, I'm returning this error instead."

The general advice, is to wait around before trying again.

This is easier said than done - any ideas?


P,S. Everything you advised me to do I did. Only X amount of threads are  created, each being re-used as necessary.

Only one socket per thread, each being re-initialised when re-used (the socket is not being explicitly closed - it is opened once- the first time it is used and found it not to be connected).

I think it's a speed issue - using a couple of threads and the problem takes longer to appear. There is no synchronisation issues, since I've removed all UI update so all the threads are doing are socket commands - the outside world doesn't know of their progress.

 

by: ciulyPosted on 2008-03-04 at 07:21:34ID: 21041770

>> This is easier said than done - any ideas?

it's not that hard actually.

repat
  do something (sendstr maybe)
  if wsagetlasterror=WSAEWOULDBLOCK then
    sleep(10)
  else
    break;
until false;

I am guessing that this is a limitation/bug in the windows socket layer, though I couldn't find anything to back it up (well, there are a ton of issues with winsock, but nothing related to many socket operations happenig in  a shortwhile (or at least I couldn't find any))

I would suggest turning to blocking sockets (since you don't need the asynchroneus socket, you beeing in a thread already).

 

by: steve-westPosted on 2008-03-04 at 07:47:15ID: 21042013

Sorry, hasn't worked

I did exactly as you suggest, but still get the error (but I don;t believe quite as often as before).

Anyway, just to comment on your example

repat
  do something (sendstr maybe)
  if wsagetlasterror=WSAEWOULDBLOCK then
    sleep(10)
  else
    break;
until false;


For the above, there's no check for the initial SendStr - if WSAEWOULDBLOCK is returned(which is what is happening) then the Sleep part is pointless.

I tried reversing this so that  the WSA... was checked for first and only outside the Repeat loop was the sendstr executed.

This did not work at all - WSAEWOULDBLOCK was always being returned so the socket just sat there...

 

by: ciulyPosted on 2008-03-04 at 08:01:36ID: 21042145

I don't get it. in that code:
- if the socket is already in wsconnecting, calling sendstr will leave it that way so wsagetlasterror after the sendstr will read it in and will sleep on it
- and if there is no wsconecting, but while sendstr is called it gets set, then the wsagetlasterror after the sendstr will read it in and will sleep on it

that's the logic. unless you work with the socket in some other palces as well, in which case you need to do the same there as well.

the idea behind using it like that and not getting the last error before calling it is that after you call sendstr you must know if it succeded or not, and if it didn't, send it again.

now, you say that you get an error. I don't know how ICS works, but how can you get an error if we are treating the error. do you mnean that you get an exception? if so, then use it like this:

repat
  try
    do something (sendstr maybe)
  except
    if wsagetlasterror=WSAEWOULDBLOCK then
      sleep(10)
    else
      break;
  end;
until false;

 

by: steve-westPosted on 2008-03-05 at 08:44:25ID: 21051896

Thanks for your help, things seem to be sorted as best as they can be.

I'm still having problems (Socket already open) re-establishing a socket connection should one become disconnected, but this is unrelated to the initial question.

Thanks again.

Steve

P.S. You need "break" just before the except in your last example...

 

by: ciulyPosted on 2008-03-05 at 11:26:07ID: 21053492

>> P.S. You need "break" just before the except in your last example...

right :D

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...