Click here to Skip to main content
Click here to Skip to main content

Power up the TCP/IP capability in your PocketPC application

, 19 Dec 2002
Rate this:
Please Sign up or sign in to vote.
Establish a TCP/IP connection to other applications.

Introduction

Everyone should have an idea on accessing Winsock in eMbedded Visual Basic 3.0. Its 100% easy and straight forward as what I did in Visual Basic. But how about eMbedded Visual C++ 3.0?

The Winsock for MS Windows CE does not support WSAAsyncSelect. Hence, we need to write a chunk of code as well as the synchronization thread to handle the incoming and outgoing data ourselves.

Using the code

The posted code is the entire sample project. So you might need to cut & paste the following function in order to utilize the piece of code in your own project. Don't worry, the code is easy to identify and all you need is to filter out all my demo project GUI interface control code.

Below are the three basic functions and the two synchronization threads you need to copy:

// Function
int  InitSocket (HWND); // Initialize the Winsock.DLL
void  OpenSocket (HWND); // Open the server side socket
void  CloseSocket(HWND); // Close the server side socket

// Synchronization Thread

// Waiting for the incoming connection request
DWORD WINAPI StartListen (LPVOID pParam); 
// Reading the incoming buffer
DWORD WINAPI ReadInBuffer (LPVOID pParam); 

Once you have copied the code, you need to call the above mentioned three functions in sequence. As each of them is to perform a specific task. Em... Lets look at the first function InitSocket as below. Basically, all it does is just initialize the Winsock component (version 1.1) by calling the WSAStartup API before we can proceed to create/use any socket.

WSADATA wsaData;

// Initliatize the Winsock dll version 1.1
if (WSAStartup(MAKEWORD(1,1), &wsaData) != 0)
{
    // Fail to initialize the winsock dll
    MessageBox(hWnd, TEXT("Fail to initialize the Winsock DLL!"), 
                       TEXT("MySocket"), MB_OK | MB_ICONEXCLAMATION);
    // Set the return value
    return 1;
}
else
    // Successful initialize the Winsock DLL
    // Set the return value
    return 0;

Second, we need to create a new socket to listen to an incoming request (connect to a host) on a specific port number and accept the connection request (establish the connection). But you will notice there is some extra code under the OpenSocket which is used to handle the GUI control for determining whether the socket going to be created is in Server mode or Client mode. This is because both will have two different logic flow and characteristics.

Hence, if the socket going to be created is in server mode, all you need is proceed to create the synchronization thread (StartListen). Else, you will need to execute the following code to establish a connection to the specific host followed by creating the ReadInBuffer synchronization thread.

NOTE: All the non-relevant GUI code is filtered out in the following display code (but not in the attached demo project code). You may need to add your own GUI control/updated code into this function.

// Reset the SOCKADDR_IN struct
memset(&sckAddress, 0, sizeof(sockaddr_in));
// Setup the sckClient socket
sckClient = socket(AF_INET, SOCK_STREAM, 0);
sckAddress.sin_port = htons(atoi(port));
sckAddress.sin_family = AF_INET;
sckAddress.sin_addr.s_addr = inet_addr(host);
if(connect(sckClient, (struct sockaddr *)&sckAddress, 
                     sizeof(sckAddress)) != SOCKET_ERROR)
// Create read input buffer thread
    hThread2 = CreateThread(NULL, 0, ReadInBuffer, hWnd, 0, &dwThreadID);
else
    // Notify user about the error
    MessageBox(hWnd, TEXT("Client~Fail to establish the connection!"), 
                          TEXT("MySocket"), MB_OK | MB_ICONEXCLAMATION);

What is inside the StartListen synchronization thread? When you look into the code, you'll find that it is an infinite do...while loop in this thread and perform a checking on the socket state on every loop until it gets a valid socket handle as show in the code below:

if(sckServer != INVALID_SOCKET)
{
    // Setup the port number, protocol & etc..
    sckAddress.sin_port = htons(atoi(port));
    sckAddress.sin_family= AF_INET;
    sckAddress.sin_addr.s_addr = INADDR_ANY;
    // Bind the socket
    bind(sckServer, (struct sockaddr *)&sckAddress, sizeof(sckAddress));

    // Listen to the specific port for 1 client connection only
    listen(sckServer, 1);

    // Start looping and check the respective port for incoming request
    do
    {
        // Socket callback status structure
        fds;
        // Maximum wait time for the "select" command
        tv.tv_sec = 1;
        tv.tv_usec = 1; 
        // Initialize the fd_set structure to NULL
        FD_ZERO (&fds);
        // Add the sckServer socket to fd_set structure
        FD_SET (sckServer, &fds);
        // Call the select command
        if (select(0, &fds, NULL, NULL, &tv) == 0)
            // Maximum wait time is expired.
            continue;
        // Check is there any incoming request/active in the fd_set structure
        // Zero mean no, else
        if (FD_ISSET(sckServer, &fds) != 0)
        {
            // Accept the incoming request
            sckClient = accept(sckServer, NULL, 0);
            // Close the existing listen socket (sckServer)
            closesocket(sckServer);
            // Reset the sckSocket variable to NULL
            sckServer = INVALID_SOCKET;
            // Update status control
            SetDlgItemText(hWnd, IDC_STATUS1, TEXT("Connected"));
            // Create read input buffer thread
            hThread2 = CreateThread(NULL, 0, ReadInBuffer, 
                                        hWnd, 0, &dwThreadID);
            // Self terminate this thread
            break;
        }
    }while (sckServer != INVALID_SOCKET);
}
else
    // Notify user about the error
    MessageBox(hWnd, TEXT("Server~Fail to open the socket!"), 
                  TEXT("MySocket"), MB_OK | MB_ICONEXCLAMATION);

At this stage, you still can not receive any data from the host (client) connection. So, the ReadInBuffer synchronization thread is heard of the entire demo application which enables you to receive any data from host (client) connection.

Hence, lets take a look on the ReadInBuffer coding and understand more about its operation.

HWND hWnd = NULL;
char *Buff=NULL;
TCHAR *wBuff=NULL;

int err;

// map the pass in variable
hWnd = (HWND)pParam;
// Create new string buffer
wBuff = new TCHAR[1024];
Buff = new char[1024];

if (sckClient != INVALID_SOCKET )
{
    // Loop until no data in the input buffer
    while (true)
    {
        // Reset the allocated string buffer
        memset(wBuff, TEXT('\0'), 1024*sizeof(TCHAR));
        memset(Buff, '\0', 1024);
        // Read the data from valid socket
        err = recv(sckClient, Buff, 1024, 0);
        if (err == SOCKET_ERROR || err <= 0)
        {
            // Remote terminal reset the socket connection
            CloseSocket(hWnd);
            // Self terminate the thread
            break;
        }
        else
        {
            // Convert from MultiByte to UNICODE
            mbstowcs(wBuff, Buff, 1024);
            // Display the received data
            SetDlgItemText(hWnd, IDC_EDIT3, wBuff);
        }
    }
}

// Release the used memory
delete Buff;
// Self terminate the thread
ExitThread(WM_QUIT);
// Set the return value
return 0;

From the above code, there is an infinite while loop which will constantly check the socket status and it will break the looping when there is an invalid socket detected.

Last, we must destroy the socket when not in use or upon detecting the host (client) connection is lost. Therefore, the CloseSocket function is straight forward as shown below.

// Validate
if(sckServer != INVALID_SOCKET)
{
    // Close the current server side socket
    if (closesocket(sckServer) == 0)
    // Reset the sckServer
        sckServer = INVALID_SOCKET;
    else
        // Notify user about the error
        MessageBox(hWnd, TEXT("Server~Fail to close the socket."), 
                        TEXT("MySocket"), MB_OK | MB_ICONEXCLAMATION);
}

P.S If you need to get the local machine IP address, all you need is call the GetLocalIP function as included in the demo application.

Will do.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

CT CHANG
Web Developer
Malaysia Malaysia
Hackzai was graduated from Double-E, and being certified as MCSD (VS6) at spring 2003. But move forward with ASP.NET, VB.NET, C#, Silverlight, LINQ, XML

Comments and Discussions

 
QuestionHow can I download files from internet to my ppc [modified] Pinmemberenderchen26-Aug-07 20:39 
GeneralSame but don't woek PinmemberBandoleiro15-Jun-07 5:18 
QuestionLink Error PinmemberAllan Yan1-Mar-07 18:05 
AnswerRe: Link Error PinmemberAllan Yan1-Mar-07 20:33 
programm fixed up. add "winsock.lib" in linker.
in these steps: project -> setting -> then select "link" tab,in the object/library modules add winsock.lib. build and execute,then U can get it. Smile | :)
QuestionNo connection to Internet by Pocket PC 2003 Emulator PinmemberCsharper200613-Jul-06 10:40 
QuestionActiveSync and establish second connection? PinmemberEugen Wiebe1-Jun-06 4:34 
QuestionHow to run thIs example program ... PinmemberVijai5622-Oct-05 0:43 
AnswerRe: How to run thIs example program ... Pinmemberdt.lcr29-Mar-06 15:28 
AnswerRe: How to run thIs example program ... Pinmembervijasi29-Mar-06 17:40 
QuestionGPRS? PinsussDonovan Hutcheon8-Sep-05 22:19 
QuestionGPRS? PinsussDonovan Hutcheon8-Sep-05 22:19 
AnswerRe: GPRS? PinmemberTili30-Oct-05 17:58 
GeneralWince Message Queues Opening Problem Pinmemberindianstar21-Jun-05 0:22 
GeneralGetting Linking Error Pinmemberindianstar9-Jun-05 2:51 
GeneralRe: Getting Linking Error Pinmemberhackzai9-Jun-05 14:49 
GeneralRe: Getting Linking Error Pinmemberindianstar9-Jun-05 18:56 
GeneralRe: Getting Linking Error Pinmemberhackzai12-Jun-05 17:52 
GeneralQuestion PinmemberHing29-Mar-04 19:00 
GeneraleVC 4.0 Pinmembertrajecto11-Nov-03 18:56 
GeneralRe: eVC 4.0 PinmemberK-PAX25-Dec-03 0:35 
GeneralRe: eVC 4.0 Pinmemberjundar18-Jan-05 1:23 
GeneralFTP connection PinsussSimone Sanfilippo15-Oct-03 23:22 
QuestionHow can I use TCP/IP for transfer file PinmemberSimone197629-May-03 23:33 
AnswerRe: How can I use TCP/IP for transfer file PinmemberK-PAX30-May-03 0:28 
GeneralRe: How can I use TCP/IP for transfer file PinmemberSimone197630-May-03 0:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 20 Dec 2002
Article Copyright 2002 by CT CHANG
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid