Microsoft KB Archive/830597

= How to send multiple-byte out-of-band data by using Winsock =

Article ID: 830597

Article Last Modified on 1/19/2007

-

APPLIES TO


 * Microsoft Windows 2000 Professional Edition
 * Microsoft Windows 2000 Server
 * Microsoft Windows 2000 Advanced Server
 * Microsoft Windows 2000 Datacenter Server
 * Microsoft Windows XP Home Edition
 * Microsoft Windows XP Professional
 * Microsoft Windows Server 2003, Standard Edition (32-bit x86)
 * Microsoft Windows Server 2003, Enterprise Edition (32-bit x86)
 * Microsoft Windows Server 2003, Datacenter Edition (32-bit x86)

-





SUMMARY
''Sometimes you must send urgent out-of-band (OOB) data to your receivers. Receivers are any users or any applications that receive the data. You want this OOB data treated as higher-priority data than any normal data that you may send. If the OOB data that you want to send is one byte, you can use the select function to look for OOB data. You can use the recv function to read the data.

However, in Transmission Control Protocol (TCP), the OOB data block is always one byte. Therefore, if you send multiple-byte OOB data, only the last byte of the OOB data is retrieved. The remaining data is treated like normal data.

This article uses sample code to describe how to send multiple-byte OOB data by using Microsoft Windows Socket (Winsock).''



IN THIS TASK

 * INTRODUCTION
 * Create a client application
 * Create a server application
 * Display the sample code for the client application, Myclient.cpp
 * Display the sample code for the server application, Myserver.cpp
 * Test the sample
 * REFERENCES



INTRODUCTION
This article describes how to send multiple-bytes (chars) out-of-band data by using Winsock. The sample applications are created in Microsoft Visual C++.

Because this OOB mechanism is not directly supported at the Microsoft Windows socket level, you must implement this OOB mechanism at the application level. This is not true OOB data. In this sample application, you create two sockets on the client side, also known as the sender side, to send OOB data and normal data. On the server side, also known as the receiver side, you use two sockets to process the data in two threads. One thread is for OOB data. The other thread is for normal data.

To simulate the OOB mechanism, you must synchronize these two threads. Make sure that the thread that processes OOB data has higher priority than the thread that processes normal data.

Note This sample application describes one way to send multi-byte OOB data. You may have to revise the code to make the code work in your environment.

back to the top

Create a client application
  Create a client application. In this client application, the following sample code describes how to create two sockets: SOCKET myOOBSocket = INVALID_SOCKET; SOCKET myNormalSocket = INVALID_SOCKET;

myOOBSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); myNormalSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); The myOOBSocket variable is used to send OOB data. The myNormalSocket variable is used to send normal data.   Because the data that the myOOBSocket variable sends is not true OOB data, you must have a way to tell the server what kind of data that the socket is supposed to send before you start sending data. The following sample code describes how to send an initial character to notify the server about what kind of data that will be sent. Use &quot;U&quot; for OOB data and use &quot;N&quot; for normal data. int nErr, nSize; nErr = connect(myNormalSocket, (SOCKADDR *)&remoteIp, sizeof(remoteIp)); //Look for a potential error here. //&quot;remoteIp&quot; is the remote address. nSize = send(myNormalSocket, &quot;N&quot;,1, 0); //Look for a potential error here.

nErr = connect(myOOBSocket, (SOCKADDR *)&remoteIp, sizeof(remoteIp)); //Look for a potential error here. nSize = send(myOOBSocket,&quot;U&quot;,1, 0); //Look for a potential error here.   The following sample code describes how to make the client application monitor the input from the user. The client application sends uppercase characters as OOB data. Duplicate every input character to compose a multiple-byte string. for { int ch = _getch; _putch( ch ); if (ch=='.') { shutdown(myOOBSocket, 2); shutdown(myNormalSocket,2); break; }       char buf[10]; memset(buf, ch, sizeof(buf));

if (isupper(ch)) { nSize = send(myOOBSocket, buf, sizeof(buf), 0); //Do not use the MSG_OOB flag. Send it as normal data. } else { nSize = send(myNormalSocket, buf, sizeof(buf), 0); }   ... } 

Display the sample code for the client application, Myclient.cpp

back to the top

Create a server application
  On the server side, the following sample code describes how to create a listener socket to monitor the port that is used for communication: int nErr; SOCKET myListener = INVALID_SOCKET;

myListener = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); //Look for a potential return error here.

nErr = bind(myListener,(SOCKADDR *)&localIp,sizeof(localIp)); //Look for a potential return error here. //&quot;localIp&quot; is the local address of the server.

nErr = listen(myListener, 5); //Look for a potential return error here.   The following sample code describes how to call the accept function to make the listener socket wait for incoming connection tries: for { struct sockaddr_in remoteIp; SOCKET remoteSocket = INVALID_SOCKET; int nAddrLen = sizeof(SOCKADDR);

remoteSocket = accept(myListener, (SOCKADDR *)(&remoteIp), &nAddrLen); //&quot;remoteIp&quot; is a pointer to a buffer that receives //the address of the connecting entity.

BYTE buffer[1+1]; int recv_len=recv(remoteSocket,(char *)&buffer,1,0); //This supposes that the client sockets will send //&quot;U&quot; or &quot;N&quot; as the initial character.

buffer[recv_len] = '\0'; if(strcmp((char *)buffer,&quot;U&quot;)==0) hThread=CreateThread(0,0,OOBHandler,(LPVOID)remoteSocket, 0, &dwThreadId); //Create a new thread to process incoming OOB data. &quot;OOBHandler&quot; is a        //pointer to the OOB data handler. else if(strcmp((char *)buffer,&quot;N&quot;)==0) hThread=CreateThread(0,0,NormalHandler,(LPVOID)remoteSocket, 0, &dwThreadId); //Create a new thread to process incoming normal data. &quot;NormalHandler&quot; is        //a pointer to the normal data handler. ... } </li>  To simulate the OOB mechanism, you must synchronize these two threads. In this sample application, use a global Event object to do this. Put the following statement at the top of the file. //Create a manual-reset event object. hRecvEvent=CreateEvent(NULL,TRUE,TRUE,&quot;RecvEvent&quot;); </li> Create the OOB handler that is executed by a separate thread. In this handler, you use the select function to detect when data arrives. When data arrives, follow these steps:   Call the ResetEvent function to set the hRecvEvent event object to the non-signaled state. ResetEvent(hRecvEvent); This blocks the normal data handler that is executed in another thread. </li>  Call the revc function to read the data. recv(remoteSocket,(char *)&buffer,sizeof(buffer) - 1,0); </li>  Because more data may be sent than the buffer can hold, call the recv function again, together with the MSG_PEEK flag, to determine whether any data is available on the wire. recv(remoteSocket,(char *)&buffer,sizeof(buffer)-1,MSG_PEEK); Use either of the following methods, depending on whether there is data pending to be read or not: <ul>  If no data is pending to be read, call the SetEvent function to set the specified event object to the signaled state. SetEvent(hRecvEvent); When you do this, the normal data handler thread can resume. The normal data handler thread waits for the hRecvEvent event object before the normal data handler thread resumes. </li> If data is still pending to be read, call the recv function again to read the remaining data. Then, look again for pending data.</li></ul> </li></ol>

Repeat steps 4a through 4c until all pending data has been read.</li>  Create the normal data handler. This handler is similar to the OOB data handler except that the normal data handler calls the WaitForSingleObject function when the normal data handler detects that data has arrived. WaitForSingleObject(hRecvEvent,INFINITE); //You can set the interval parameter to a specific value if you do not want //the normal data handler to wait for the OOB handler indefinitely when OOB data arrives continuously. </li></ol>

Display the sample code for the server application, Myserver.cpp

back to the top

Display the sample code for the client application, Myclient.cpp
Note You must include a reference to the Winsock Library file, Ws2_32.lib, to make the code compile.
 * 1) include <stdio.h>
 * 2) include <stdlib.h>
 * 3) include <conio.h>
 * 4) include <assert.h>
 * 5) include <winsock.h>

main(int argc, char *argv[]) {   int nErr, nSize; WSADATA wsaData; SOCKET myOOBSocket = INVALID_SOCKET; SOCKET myNormalSocket = INVALID_SOCKET; unsigned short nPort; // Listen for the port number. struct sockaddr_in remoteIp; if (argc!=3) {       printf(&quot;TcpDemoC <RemoteIp> <Port>\n&quot;); return 0; }

// The Init Socket API. nErr = WSAStartup(MAKEWORD(1,1),&wsaData); assert(nErr==0); nPort = (unsigned short)atol(argv[2]); myOOBSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); assert(myOOBSocket!=INVALID_SOCKET);

myNormalSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); assert(myNormalSocket!=INVALID_SOCKET); // Connect to the remote address. remoteIp.sin_family = AF_INET; remoteIp.sin_port = htons(nPort);; remoteIp.sin_addr.S_un.S_addr = inet_addr(argv[1]); nErr = connect(myOOBSocket, (SOCKADDR *)&remoteIp, sizeof(remoteIp)); if (nErr == SOCKET_ERROR) { printf(&quot;Connect failed because of %lX\n&quot;, WSAGetLastError); goto Cleanup; }

nSize = send(myOOBSocket,&quot;U&quot;,1, 0); if (nSize == SOCKET_ERROR) { printf(&quot;Send failed because of %lX\n&quot;, WSAGetLastError); goto Cleanup; }   nErr = connect(myNormalSocket, (SOCKADDR *)&remoteIp, sizeof(remoteIp)); if (nErr == SOCKET_ERROR) { int error = WSAGetLastError; printf(&quot;Connect failed because of %lX\n&quot;, error); goto Cleanup; }   nSize = send(myNormalSocket, &quot;N&quot;,1, 0); if (nSize == SOCKET_ERROR) { printf(&quot;Send failed because of %lX\n&quot;, WSAGetLastError); goto Cleanup; }

printf(&quot;Read for input:\n&quot;); for { int ch = _getch; _putch( ch ); if (ch=='.') { shutdown(myOOBSocket, 2); shutdown(myNormalSocket,2); break; }       char buf[10]; memset(buf, ch, sizeof(buf));

if (isupper(ch)) { nSize = send(myOOBSocket, buf, sizeof(buf), 0); }else{ nSize = send(myNormalSocket, buf, sizeof(buf), 0); }

if (nSize == SOCKET_ERROR) { printf(&quot;Send failed because of %lX\n&quot;, WSAGetLastError); break; }   }    Sleep(1000); Cleanup: if (myOOBSocket!=INVALID_SOCKET) closesocket(myOOBSocket); if (myNormalSocket!=INVALID_SOCKET) closesocket(myNormalSocket); WSACleanup; return 0; } back to the top

Display the sample code for the server application, Myserver.cpp
Note You must include a reference to the Winsock Library file, Ws2_32.lib, to make the code compile.
 * 1) include <windows.h>
 * 2) include <stdio.h>
 * 3) include <stdlib.h>
 * 4) include <winsock.h>
 * 5) include <assert.h>

// Usage: myserver

HANDLE hRecvEvent;

DWORD WINAPI OOBHandler(LPVOID lpParam) {   int nErr, nRecv_len; BYTE buffer[10 + 1]; BOOL bClosing=FALSE; fd_set fdread;

SOCKET remoteSocket=(SOCKET)lpParam; unsigned long ul=1; int nRet = ioctlsocket(remoteSocket, FIONBIO, &ul); if(SOCKET_ERROR==nRet){ printf(&quot;Socket failed: %d\n&quot;, WSAGetLastError); return 1; }

printf(&quot;Waiting&quot;); for (int i=0; i<10; i++) { printf(&quot;.&quot;); Sleep(1000); }   printf(&quot;The OOB handler is ready!\n&quot;);

while (!bClosing){ //Always clear the set before you call the select method. FD_ZERO(&fdread); //Add sockets to the sets. FD_SET(remoteSocket, &fdread); nErr=select(0,&fdread,0,0,0); if(nErr==SOCKET_ERROR) {           printf(&quot;Select failed: %d\n&quot;,WSAGetLastError); return 1; }

if(FD_ISSET(remoteSocket,&fdread)){ ResetEvent(hRecvEvent); while(1) {               nRecv_len=recv(remoteSocket,(char *)&buffer,sizeof(buffer) - 1,0); if(nRecv_len==0){ bClosing=TRUE; printf(&quot;The connection is closed!\n&quot;); break; }           buffer[nRecv_len] = '\0'; printf(&quot;[OOB]: %s\n&quot;, buffer); nRecv_len=recv(remoteSocket,(char *)&buffer,sizeof(buffer)-1,MSG_PEEK); if (nRecv_len==SOCKET_ERROR) { if(WSAGetLastError==WSAEWOULDBLOCK) break; else printf(&quot;Recv failed. Win32 error is 0x%lx\n&quot;, WSAGetLastError); }           }            SetEvent(hRecvEvent); }    }    return 0; }

DWORD WINAPI NormalHandler(LPVOID lpParam) {   int nErr,nRecv_len; BYTE buffer[10 + 1]; fd_set fdread;

SOCKET remoteSocket=(SOCKET)lpParam;

printf(&quot;Waiting&quot;); for (int i=0; i<10; i++) { printf(&quot;*&quot;); Sleep(1000); }   printf(&quot;Normal handler ready!\n&quot;);

while(1) { //Always clear the set before you call the select method. FD_ZERO(&fdread); //Add sockets to the sets. FD_SET(remoteSocket, &fdread);

nErr=select(0,&fdread,0,0,0); if(nErr==SOCKET_ERROR){ printf(&quot;Select failed: %d\n&quot;,WSAGetLastError); return 1; }

if(FD_ISSET(remoteSocket,&fdread)){ WaitForSingleObject(hRecvEvent,INFINITE); nRecv_len=recv(remoteSocket,(char *)&buffer,sizeof(buffer) - 1,0); if (nRecv_len==SOCKET_ERROR) { printf(&quot;Recv failed. Win32 error is 0x%lx\n&quot;, WSAGetLastError); return 1; }           if(nRecv_len==0){ printf(&quot;Connection Closed!\n&quot;); break; }           buffer[nRecv_len] = '\0'; printf(&quot;[Normal]: %s\n&quot;, buffer); }   }    return 0; }

int main(int argc, char *argv[]) {   WSADATA wsaData; int nErr; SOCKET myListener = INVALID_SOCKET; struct sockaddr_in localIp; unsigned short nPort; DWORD dwThreadId; HANDLE hThread=NULL;

if (argc!=2) {       printf(&quot;MyServer <Port>\n&quot;); return 0; }   nPort = (unsigned short)atol(argv[1]);

nErr = WSAStartup(MAKEWORD(2,0),&wsaData); assert(nErr==0); assert(wsaData.wVersion == MAKEWORD(2,0));

myListener = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); assert(myListener!=INVALID_SOCKET);

// Bind the listen socket to any local IP address. localIp.sin_family = AF_INET; localIp.sin_port = htons(nPort);; localIp.sin_addr.S_un.S_addr = INADDR_ANY;

nErr = bind(myListener,(SOCKADDR *)&localIp,sizeof(localIp)); assert(nErr!=SOCKET_ERROR);

nErr = listen(myListener, 5); assert(nErr==0);

//Create a manual-reset event object. hRecvEvent=CreateEvent(NULL,TRUE,TRUE,&quot;RecvEvent&quot;); if (hRecvEvent == NULL) {        printf(&quot;CreateEvent failed with error 0x%lx\n&quot;, GetLastError); return 1; }

printf(&quot;The server is ready!\n&quot;);

for { struct sockaddr_in remoteIp; SOCKET remoteSocket = INVALID_SOCKET; int nAddrLen = sizeof(SOCKADDR);

remoteSocket = accept(myListener, (SOCKADDR *)(&remoteIp), &nAddrLen); if(remoteSocket == INVALID_SOCKET) { int error = WSAGetLastError; printf(&quot;Accept failed. Win32 error is 0x%lx\n&quot;, GetLastError); goto Cleanup; } else { printf(&quot;Connected from %d.%d.%d.%d:%d\n&quot;,                remoteIp.sin_addr.S_un.S_un_b.s_b1,                remoteIp.sin_addr.S_un.S_un_b.s_b2,                remoteIp.sin_addr.S_un.S_un_b.s_b3,                remoteIp.sin_addr.S_un.S_un_b.s_b4,                ntohs(remoteIp.sin_port));

BYTE buffer[1+1]; int nRecv_len=recv(remoteSocket,(char *)&buffer,1,0); if (nRecv_len==SOCKET_ERROR) { printf(&quot;Recv failed. Win32 error is 0x%lx\n&quot;, WSAGetLastError); return 1; }           buffer[nRecv_len] = '\0'; if(strcmp((char *)buffer,&quot;U&quot;)==0) hThread=CreateThread(0,0,OOBHandler,(LPVOID)remoteSocket, 0, &dwThreadId); else if(strcmp((char *)buffer,&quot;N&quot;)==0) hThread=CreateThread(0,0,NormalHandler,(LPVOID)remoteSocket, 0, &dwThreadId); if(hThread==0){ printf(&quot;CreateThread failed: %d\n&quot;,GetLastError); return 1; }           CloseHandle(hThread); }   }    closesocket(myListener);

Cleanup: WSACleanup; return 0; } back to the top

Test the sample
 At a command prompt, type Myserver.exe 4444 to start the server on port 4444.

The server application displays the following message and then waits for clients:

The server is ready!

</li> In a different Command Prompt window, type myClient  4444 to start the client.

Note The placeholder  is a placeholder for the IP address of the server.</li> The server displays a message that is similar to the following:

Waiting.Waiting*..*

When you receive the previous message, you must type aBcDeFgHi on the client within 10 seconds before the server continues.</li></ol>

After about 10 seconds, the server displays the following:

[OOB]: BBBBBBBBBB

[OOB]: DDDDDDDDDD

[OOB]: FFFFFFFFFF

[OOB]: HHHHHHHHHH

[Normal]: aaaaaaaaaa

[Normal]: cccccccccc

[Normal]: eeeeeeeeee

[Normal]: gggggggggg

[Normal]: iiiiiiiiii

back to the top

<div class="references_section">