IrSock Client Application
9/8/2008
O procedimento básico para usar IrSock é semelhante de sockets do Windows (Winsock). IrSock usa apenas o método de comunicação Connection-Oriented Soquete transmitir.
Para criar e usar um Soquete com um aplicativo cliente
Abrir um Soquete transmitir com Soquete, como com o aplicativo servidor. Usar AF_IRDA para o parâmetro formato endereço, SOCK_STREAM para o tipo e NULL para o parâmetro protocolo
Procure o disponível dispositivos e recuperar seu endereço com getsockopt. Para obter mais informações, consulte Descobrir dispositivos com IrSock.
Conectar-se ao servidor de conexão função com SOCKADDR_IRDA para o parâmetro nome.
Feche o Soquete com closesocket.
Para obter informações sobre como criar um aplicativo de servidor, consulte O aplicativo do servidor IrSock
O seguinte amostra de código mostra como um cliente IrSock abre um Soquete e torna cinco tenta localizar um servidor. Se nenhum servidor for localizado, o cliente exibe uma caixa diálogo para informar o usuário da falha. Quando um servidor for detectado, o cliente consulta o servidor para seu identificador dispositivo e envia uma saudação para o serviço nomeado Meu servidor. Ele, em seguida, aguarda o servidor para responder, exibe uma caixa mensagem com a resposta e fecha o Soquete.
#include <windows.h>
#include <af_irda.h>
#define NUMRETYR 5 // Maximum number of retries
int WINAPI WinMain (
HINSTANCE hInstance, // Handle to the current instance
HINSTANCE hPrevInstance,// Handle to the previous instance
LPTSTR lpCmdLine, // Pointer to the command line
int nCmdShow) // Show window state.
{
SOCKET sock; // Socket bound to the server
DEVICELIST devList; // Device list
SOCKADDR_IRDA address = {AF_IRDA, 0, 0, 0, 0, "IRServer"};
// Specifies the server socket address
int iCount = 0, // Number of retries
index = 0, // Integer index
iReturn, // Return value of recv function
iDevListLen = sizeof (devList);
// Size of the device list
char szClientA[100]; // ASCII string
TCHAR szClientW[100]; // Unicode string
TCHAR szError[100]; // Error message string
// Create a socket that is bound to the server.
if ((sock = socket (AF_IRDA, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
wsprintf (szError, TEXT("Allocating socket failed. Error: %d"),
WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
return FALSE;
}
// Initialize the number of devices to zero.
devList.numDevice = 0;
while ( (devList.numDevice == 0) && (iCount <= NUMRETYR))
{
// Retrieve the socket option.
if (getsockopt (sock, SOL_IRLMP, IRLMP_ENUMDEVICES,
(char *)&devList, &iDevListLen) == SOCKET_ERROR)
{
wsprintf (szError, TEXT("Server could not be located, getsockopt")
TEXT(" failed. Error: %d"), WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
closesocket (sock);
return FALSE;
}
iCount++;
// Wait one second before retrying.
Sleep (1000);
}
if (iCount > NUMRETYR)
{
MessageBox (NULL, TEXT ("Server could not be located!"),
TEXT ("Error"), MB_OK);
closesocket (sock);
return FALSE;
}
// Get the server socket address.
for (index = 0; index <= 3; index++)
{
address.irdaDeviceID[index] = devList.Device[0].irdaDeviceID[index];
}
// Establish a connection to the socket.
if (connect (sock, (struct sockaddr *)&address,
sizeof (SOCKADDR_IRDA)) == SOCKET_ERROR)
{
wsprintf (szError,
TEXT("Connecting to the server failed. Error: %d"),
WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
closesocket (sock);
return FALSE;
}
// Send a string from the client socket to the server socket.
if (send (sock, "To Server.", strlen ("To Server.") + 1, 0)
== SOCKET_ERROR)
{
wsprintf (szError,
TEXT("Sending data to the server failed. Error: %d"),
WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
}
// Receive data from the server socket.
iReturn = recv (sock, szClientA, sizeof (szClientA), 0);
// Check if there is any data received. If there is, display it.
if (iReturn == SOCKET_ERROR)
{
wsprintf (szError, TEXT("No data is received, recv failed.")
TEXT(" Error: %d"), WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Client"), MB_OK);
}
else if (iReturn == 0)
{
MessageBox (NULL, TEXT("Finished receiving data"), TEXT("Client"),
MB_OK);
}
else
{
// Convert the ASCII string to a Unicode string
szServerA[99] = 0;
MultiByteToWideChar(CP_ACP, 0, szServerA, -1,
szServerW, sizeof(szServerW)/sizeof(szServerW[0]));
// Display the string received from the server.
MessageBox (NULL, szClientW, TEXT("Received From Server"), MB_OK);
}
// Close the socket.
closesocket (sock);
return 0;
}
See Also
Concepts
IrSock Server Application
Creating an Infrared Winsock Application
IrDA Application Development