Library tutorials & articles

Introduction to TCP/IP

Blocking vs. Non-Blocking Sockets

One of the first issues that you’ll encounter when developing your Windows Sockets applications is the difference between blocking and non-blocking sockets. Whenever you perform some operation on a socket, it may not be able to complete immediately and return control back to your program. For example, a read on a socket cannot complete until some data has been sent by the remote host. If there is no data waiting to be read, one of two things can happen: the function can wait until some data has been written on the socket, or it can return immediately with an error that indicates that there is no data to be read.

The first case is called a blocking socket. In other words, the program is "blocked" until the request for data has been satisfied. When the remote system does write some data on the socket, the read operation will complete and execution of the program will resume. The second case is called a non-blocking socket, and requires that the application recognize the error condition and handle the situation appropriately. Programs that use non-blocking sockets typically use one of two methods when sending and receiving data. The first method, called polling, is when the program periodically attempts to read or write data from the socket (typically using a timer). The second, and preferred method, is to use what is called asynchronous notification. This means that the program is notified whenever a socket event takes place, and in turn can respond to that event. For example, if the remote program writes some data to the socket, a "read event" is generated so that program knows it can read the data from the socket at that point.

For historical reasons, the default behavior is for socket functions to "block" and not return until the operation has completed. However, blocking sockets in Windows can introduce some special problems. For 16-bit applications, the blocking function will enter what is called a "message loop" where it continues to process messages sent to it by Windows and other applications. Since messages are being processed, this means that the program can be re-entered at a different point with the blocked operation parked on the program's stack. For example, consider a program that attempts to read some data from the socket when a button is pressed. Because no data has been written yet, it blocks and the program goes into a message loop. The user then presses a different button, which causes code to be executed, which in turn attempts to read data from the socket, and so on.

Blocking socket functions can introduce a different type of problem in 32-bit applications because blocking functions will prevent the calling thread from processing any messages sent to it. Since many applications are single-threaded, this can result in the application being unresponsive to user actions. To resolve the general problems with blocking sockets, the Windows Sockets standard states that there may only be one outstanding blocked call per thread of execution. This means that 16-bit applications that are re-entered (as in the example above) will encounter errors whenever they try to take some action while a blocking function is already in progress. With 32-bit programs, the creation of worker threads to perform blocking socket operations is a common approach, although it introduces additional complexity into the application.

The SocketWrench control facilitates the use of non-blocking sockets by firing events. For example, a Read event is generated whenever the remote host writes on the socket, which tells your application that there is data waiting to be read. The use of non-blocking sockets will be demonstrated in the next section, and is one of the key areas in which a control has a distinct advantage over coding directly against the Windows Sockets API.

In summary, there are three general approaches that can be taken when building an application with the control in regard to blocking or non-blocking sockets:

  • Use a blocking (synchronous) socket. In this mode, the program will not resume execution until the socket operation has completed. Blocking sockets in 16-bit application will allow it to be re-entered at a different point, and 32-bit applications will stop responding to user actions. This can lead to complex interactions (and difficult debugging) if there are multiple active controls in use by the application.
  • Use a non-blocking (asynchronous) socket, which allows your application to respond to events. For example, when the remote system writes data to the socket, a Read event is generated for the control. Your application can respond by reading the data from the socket, and perhaps send some data back, depending on the context of the data received.
  • Use a combination of blocking and non-blocking socket operations. The ability to switch between blocking and non-blocking modes "on the fly" provides a powerful and convenient way to perform socket operations. Note that the warning regarding blocking sockets also applies here.

If you decide to use non-blocking sockets in your application, it’s important to keep in mind that you must check the return value from every read and write operation, since it is possible that you may not be able to send or receive all of the specified data. Frequently, developers encounter problems when they write a program that assumes a given number of bytes can always be written to, or read from, the socket. In many cases, the program works as expected when developed and tested on a local area network, but fails unpredictably when the program is released to a user that has a slower network connection (such as a serial dial-up connection to the Internet). By always checking the return values of these operations, you insure that your program will work correctly, regardless of the speed or configuration of the network.

AddThis

Comments

  1. 25 Aug 2006 at 14:25

    hi

    This is possible using threads in the client program. the client can generate parallel connections using threads. so u can create multiple clients in the same system.


    In the server side, you use two sockets. One for receive the data and another for response to corresponding clients. Use the FDSET, FDISSET functions to achieve this apps. This is reliable one
    Hope I may answered your question.

    Karthik









  2. 05 Apr 2006 at 08:19

    hi i want to make socket connection for the multiple clients like i want to send the data to the server to the multiple clients how i will be able to do that. IS there anybody else who can help me. I am able to do that by socket programming but only in single system when i want to do that on multiple system then it is not possible.is there any one? its very needed.................................... thanks and bye

     

  3. 06 Feb 2006 at 12:22

    Hi,


    Iam developing the socket application.In this the remote host is sending messages.But iam not able to pick all the messages sent by the remote host.If remote is sending 10 msgs,then iam able to pick 2 or 3 msgs.pls tell me,what could be the reason for that asap.


    Thank you.


  4. 15 Dec 2004 at 02:56

    there would b two applications one will be at server the other will be at client side
    i m sending this code asuming that u have some prior knowledge about network programming
    include this code at server side



    Private Sub listen_Click()


    Winsock1.LocalPort = 1002
    Winsock1.listen


    End Sub



    Private Sub cmdsend_Click()
    Winsock1.SendData chattxtbox.Text
    txtwindow.Text = txtwindow.Text & vbNewLine & chattxtbox.Text
    chattxtbox.Text = ""



    txtwindow.SelStart = Len(txtwindow)



    End Sub


    Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
    Winsock1.Close
    Winsock1.Accept requestID


    End Sub


    Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
    Dim txtwindowdata As String
    Winsock1.GetData txtwindowdata


    txtwindow.Text = txtwindow.Text & vbNewLine & txtwindowdata
    txtwindow.SelStart = Len(txtwindow)




    End Sub


    //include this one at client siderivate Sub cmdconnect_Click()


    Winsock1.RemoteHost = "127.0.0.1"
    Winsock1.RemotePort = 1002
    Winsock1.Connect



    End Sub





    Private Sub cmdsend_Click()
    Winsock1.SendData chattxtbox.Text
    rectxtwindow.Text = rectxtwindow.Text & vbNewLine & rectxtwindow.Text
    chattxtbox.Text = ""



    End Sub



    Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
    Dim txtfromserver As String
    Winsock1.GetData txtfromserver
    rectxtwindow.Text = rectxtwindow.Text & vbNewLine & txtfromserver
    rectxtwindow.SelStart = Len(rectxtwindow)




    End Sub


    Private Sub Winsock1_Connect()
    MsgBox "Connecting to Server....Plz stay  far n WAIT"
    End Sub



    this will make a client server chat applicatin with in a LAN


  5. 27 Aug 2004 at 01:17

    Hi. I read ur message. I'm doing a (socket programming) chatty client/server messenger program too and I need lots of help. I heard you have done it. Could u send me ur source code and i could refer to it. Thanks alot it will help me greatly. By the way i'm using tcp.  

  6. 24 Mar 2004 at 15:14

    I ran into this problem a long time ago, what you need to do is throw in a DoEvents call in the place where your server is handling the incomming and outgoing traffic.  I haven't made anything like that for awhile, but I'm pretty sure you do it in your loops, like:


    example:


    for each.. blah blah
    Winsock1.SendData blah
    DoEvents
    end for

  7. 25 Jan 2004 at 07:53

    Hi...


    im new to tcp programming using winsock control in Vusual Basic.
    i tried a client server chat program, in which there is a client program running and its
    communicting with a server program. when i tried with two clients communicating thru a server program..its not working...can you help me....please send the source code also..


    By
    Faisal

  8. 25 Aug 2003 at 08:58

    I only speak a lite bit of English


    I need to know the name of the file on Windows to define a
    new LocalPort (UDP port) for a new application (Client/Server) of
    Files.


    Mi lenguaje es el Castellano.


    Thanks Javier

  9. 06 May 2003 at 18:17

    If you're using SocketWrench, there's an HTTP client and server example that's included that could probably serve as a foundation for what you're interested in doing. If you have any specific questions, I'd be happy to answer them for you.

  10. 23 Apr 2003 at 06:07

    I am a new member and my question might have been asked before but i can not find it in the archives.
    But if anyone would be able to help, please do. I would be greatful.
    Q: I have to create a (http like) protocol to enable the client communicate with a server. I know the basics but would be greatful for any ideas. Thanks

  11. 16 Dec 2002 at 10:20

    How are you broadcasting? Are you using TCP/IP or UDP? I have sent broadcast messages using UDP just by using the broadcast address 255.255.255.255 so that the packet goes everywhere. I had problems prior to using this when the PC's were in different domains. I dont know if this helps!

  12. 15 Nov 2002 at 16:27

    i created a client/server application using winsock, and everything works fine except if i try to send a message to all the clients from the server, only the last client actually recieves the message. after much research i found the service pack 4 for VB resolves this issue...but it only resolved the issue if i use my computer (that has VB) as the server.... i need to use a computer that does not have VB to be the server. Can anyone help me!!!!!

Leave a comment

Sign in or Join us (it's free).

Events coming up

  • Jun 16

    Code Generation 2009

    Cambridge, United Kingdom

    A developer event with a practical focus on helping people get to grips with code generation tools and technologies.