You are on page 1of 9

TCP Server #include <cvirte.h> #include <stdio.h> #include <stdlib.h> #include <tcpsupp.h> #include <string.h> #include <utility.

h> #include <userint.h> #include "server.h" int CVICALLBACK ServerTCPCB (unsigned handle, int event, int error, void *callbackData); static void ReportTCPError (void); static unsigned int g_hconversation; static int g_hmainPanel = 0; static int g_TCPError = 0; int main (int argc, char *argv[]) { int portNum; char tempBuf[256] = {0}; int registered = 0; if (InitCVIRTE (0, argv, 0) == 0) return -1; if ((g_hmainPanel = LoadPanel(0, "server.uir", MAINPNL)) < 0) return -1; DisableBreakOnLibraryErrors(); PromptPopup ("Port Number?", "Type the port number on which you would like to register " "this server application.\n\n(example: 10000)", tempBuf, 31); portNum = atoi (tempBuf); SetWaitCursor (1); if (RegisterTCPServer (portNum, ServerTCPCB, 0) < 0) MessagePopup("TCP Server", "Server registration failed!"); else { registered = 1; SetWaitCursor (0); SetCtrlVal (g_hmainPanel, MAINPNL_ONLINE, 1); if ((g_TCPError=( GetTCPHostAddr (tempBuf, 256))) < 0) { ReportTCPError(); goto Done; } else SetCtrlVal (g_hmainPanel, MAINPNL_SERVER_IP, tempBuf); if ((g_TCPError=( GetTCPHostName (tempBuf, 256))) < 0) { ReportTCPError(); goto Done; } else SetCtrlVal (g_hmainPanel, MAINPNL_SERVER_NAME, tempBuf); SetCtrlAttribute (g_hmainPanel, MAINPNL_STRING, ATTR_DIMMED, 1); SetCtrlVal (g_hmainPanel, MAINPNL_CONNECTED, 0); DisplayPanel (g_hmainPanel); SetActiveCtrl (g_hmainPanel, MAINPNL_STRING); RunUserInterface (); } Done: if (registered) UnregisterTCPServer (portNum); DiscardPanel (g_hmainPanel); CloseCVIRTE (); return 0; }

int CVICALLBACK TransmitCB (int panelHandle, int controlID, int event, void *callbackData, int eventData1, int eventData2) { char transmitBuf[512] = {0}; switch (event) { case EVENT_COMMIT: GetCtrlVal (panelHandle, MAINPNL_STRING, transmitBuf); strcat (transmitBuf, "\n"); SetCtrlVal (panelHandle, MAINPNL_TRANSMIT, transmitBuf); SetCtrlVal (panelHandle, MAINPNL_STRING, ""); if (ServerTCPWrite (g_hconversation, transmitBuf, strlen (transmitBuf), 1000) < 0) SetCtrlVal (panelHandle, MAINPNL_TRANSMIT, "Transmit Error\n"); break; } return 0; }

int CVICALLBACK MainPanelCB (int panel, int event, void *callbackData, int eventData1, int eventData2) { if (event == EVENT_CLOSE) QuitUserInterface (0); return 0; }

static void ReportTCPError (void) { if (g_TCPError < 0) { char messageBuffer[1024]; sprintf(messageBuffer, TCP library error message: %s\nSystem error message: %s", GetTCPErrorString (g_TCPError), GetTCPSystemErrorString()); MessagePopup ("Error", messageBuffer); } }

int CVICALLBACK ClearScreenCB (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { if (event == EVENT_COMMIT) ResetTextBox (panel, MAINPNL_RECEIVE, ""); return 0; }

int CVICALLBACK ServerTCPCB (unsigned handle, int event, int error, void *callbackData) { char receiveBuf[256] = {0}; int dataSize = sizeof (receiveBuf) - 1; char addrBuf[31]; switch (event) { case TCP_CONNECT: if (g_hconversation) { tcpChk (GetTCPPeerAddr (handle, addrBuf, 31)); sprintf (receiveBuf, "-- Refusing conection request from " "%s --\n", addrBuf); SetCtrlVal (g_hmainPanel, MAINPNL_RECEIVE, receiveBuf); tcpChk (DisconnectTCPClient (handle)); } else { g_hconversation = handle; SetCtrlVal (g_hmainPanel, MAINPNL_CONNECTED, 1); tcpChk (GetTCPPeerAddr (g_hconversation, addrBuf, 31)); SetCtrlVal (g_hmainPanel, MAINPNL_CLIENT_IP, addrBuf); tcpChk (GetTCPPeerName (g_hconversation, receiveBuf, 256)); SetCtrlVal (g_hmainPanel, MAINPNL_CLIENT_NAME, receiveBuf); sprintf (receiveBuf, "-- New connection from %s --\n", addrBuf); SetCtrlVal (g_hmainPanel, MAINPNL_RECEIVE, receiveBuf); SetCtrlAttribute (g_hmainPanel, MAINPNL_STRING, ATTR_DIMMED, 0); tcpChk (SetTCPDisconnectMode (g_hconversation, TCP_DISCONNECT_AUTO)); } break; case TCP_DATAREADY: if ((dataSize = ServerTCPRead (g_hconversation, receiveBuf, dataSize, 1000)) < 0) { SetCtrlVal (g_hmainPanel, MAINPNL_RECEIVE, "Receive Error\n"); } else { receiveBuf[dataSize] = '\0'; SetCtrlVal (g_hmainPanel, MAINPNL_RECEIVE, receiveBuf); } break; case TCP_DISCONNECT: if (handle == g_hconversation) { SetCtrlVal (g_hmainPanel, MAINPNL_CONNECTED, 0); g_hconversation = 0; SetCtrlVal (g_hmainPanel, MAINPNL_CLIENT_IP, ""); SetCtrlVal (g_hmainPanel, MAINPNL_CLIENT_NAME, ""); SetCtrlVal (g_hmainPanel, MAINPNL_RECEIVE, "-- Client disconnected --\n"); SetCtrlAttribute (g_hmainPanel, MAINPNL_STRING, ATTR_DIMMED, 1); } break; } Done: return 0; }

TCP Client #include <cvirte.h> #include <stdio.h> #include <stdlib.h> #include <tcpsupp.h> #include <string.h> #include <utility.h> #include <userint.h> #include "client.h" #define tcpChk(f) if ((g_TCPError=(f)) < 0) {ReportTCPError(); goto Done;} else int CVICALLBACK ClientTCPCB (unsigned handle, int event, int error, void *callbackData); static void ReportTCPError (void); static unsigned int g_hconversation; static int g_hmainPanel; static int g_connected = 0; static int g_TCPError = 0;

int main (int argc, char *argv[]) { int portNum; char tempBuf[256] = {0}; char portNumStr[32]; if (InitCVIRTE (0, argv, 0) == 0) return -1; if ((g_hmainPanel = LoadPanel(0, "client.uir", MAINPNL)) < 0) DisableBreakOnLibraryErrors();

goto Done;

PromptPopup ("Server Name?", "Type the name of the machine running the sample server " "application.\n\n(example: abc.xyz.com or xxx.xxx.xxx.xxx)", tempBuf, 255); PromptPopup ("Port Number?", "Type the port number that was set when starting the sample " "server application.\n\n(example: 10000)", portNumStr, 31); portNum = atoi (portNumStr); SetWaitCursor (1); if (ConnectToTCPServer (&g_hconversation, portNum, tempBuf, ClientTCPCB, NULL, 5000) < 0) MessagePopup("TCP Client", "Connection to server failed !"); else { SetWaitCursor (0); g_connected = 1; SetCtrlVal (g_hmainPanel, MAINPNL_CONNECTED, 1); tcpChk (GetTCPHostAddr (tempBuf, 256)); SetCtrlVal (g_hmainPanel, MAINPNL_CLIENT_IP, tempBuf); tcpChk (GetTCPHostName (tempBuf, 256)); SetCtrlVal (g_hmainPanel, MAINPNL_CLIENT_NAME, tempBuf); tcpChk (GetTCPPeerAddr (g_hconversation, tempBuf, 256)); SetCtrlVal (g_hmainPanel, MAINPNL_SERVER_IP, tempBuf); tcpChk (GetTCPPeerName (g_hconversation, tempBuf, 256)); SetCtrlVal (g_hmainPanel, MAINPNL_SERVER_NAME, tempBuf); DisplayPanel (g_hmainPanel); SetActiveCtrl (g_hmainPanel, MAINPNL_STRING); RunUserInterface (); } Done: if (g_connected) DisconnectFromTCPServer (g_hconversation); DiscardPanel (g_hmainPanel); CloseCVIRTE (); return 0; }

int CVICALLBACK TransmitCB (int panelHandle, int controlID, int event, void *callbackData, int eventData1, int eventData2) { char transmitBuf[512] = {0}; switch (event) { case EVENT_COMMIT: GetCtrlVal (panelHandle, MAINPNL_STRING, transmitBuf); strcat (transmitBuf, "\n"); SetCtrlVal (panelHandle, MAINPNL_TRANSMIT, transmitBuf); SetCtrlVal (panelHandle, MAINPNL_STRING, ""); if (ClientTCPWrite (g_hconversation, transmitBuf, strlen (transmitBuf), 1000) < 0) SetCtrlVal (panelHandle, MAINPNL_TRANSMIT, "Transmit Error\n"); break; } return 0; } int CVICALLBACK ClientTCPCB (unsigned handle, int event, int error, void *callbackData) { char receiveBuf[256] = {0}; int dataSize = sizeof (receiveBuf) - 1; switch (event) { case TCP_DATAREADY: if ((dataSize = ClientTCPRead (g_hconversation, receiveBuf, dataSize, 1000)) < 0) { SetCtrlVal (g_hmainPanel, MAINPNL_RECEIVE, "Receive Error\n"); } else { receiveBuf[dataSize] = '\0'; SetCtrlVal (g_hmainPanel, MAINPNL_RECEIVE, receiveBuf); } break; case TCP_DISCONNECT: MessagePopup ("TCP Client", "Server has closed connection!"); SetCtrlVal (g_hmainPanel, MAINPNL_CONNECTED, 0); g_connected = 0; MainPanelCB (0, EVENT_CLOSE, 0, 0, 0); break; } return 0; } int CVICALLBACK ClearScreenCB (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { if (event == EVENT_COMMIT) ResetTextBox (panel, MAINPNL_RECEIVE, ""); return 0; } int CVICALLBACK MainPanelCB (int panel, int event, void *callbackData, int eventData1, int eventData2) { if (event == EVENT_CLOSE) QuitUserInterface (0); return 0; } static void ReportTCPError(void) { if (g_TCPError < 0) { char messageBuffer[1024]; sprintf(messageBuffer, "TCP library error message: %s\nSystem error message: %s", GetTCPErrorString (g_TCPError), GetTCPSystemErrorString()); MessagePopup ("Error", messageBuffer); g_TCPError = 0; } }

Cliente

Servidor
RegisterTCPServer ( porta, ptr Server_callback, ptr dados) Notifica o Sistema Operacional que o programa atuar como Servidor e indica a funo que tratar os eventos de comunicao.

Pede conexo ao servidor recebendo do Sistema Operacional um handle para a conexo.

ConnectToTCPServer ( &h_conexo, porta, host, ptr Client_callback, ptr dado, timeout)

ON_CONNECT

Recebe e trata os pedidos de conexo dos clientes. Associa um handle para cada conexo.

Processa a comunicao entre cliente e servidor usando o respectivo handle.

TCP_DATAREADY ClientTCPRead ( h_conexo, ptr buffer, tam dado, timeout)

ServerTCPWrite ( h_conexo, ptr dados, tam dado, timeout)

Processa a comunicao entre servidor e cliente usando o respectivo handle.

Client_Callback TCP_DATAREADY TCP_DISCONNECT ClientTCPWrite ( h_conexo, ptr dado, tam dado , timeout)

Server_Callback ON_CONNECT TCP_DATAREADY ServerTCPRead ( h_conexo, ptr buffer, tam dado, timeout) TCP_DATAREADY TCP_DISCONNECT

Pede desconexo ao servidor liberando o respectivo handle.

DisconnectFromTCPServer ( h_conexo) TCP_DISCONNECT

Processa o pedido de desconexo do cliente liberando o respectivo handle.

Processa o aviso de desconexo enviado pelo servidor liberando o respectivo

DisconnectTCPClient ( h_conexo) TCP_DISCONNECT

Avisa ao cliente que ele ser desconectado e libera o respectivo handle.

UnregisterTCPServer ( porta);

Avisa ao Sistema Operacional que o programa est sendo encerrado.

UDP Reader #include <cvirte.h> #include <userint.h> #include <udpsupp.h> #include "toolbox.h" #include "UDPReader.h" #include "UDPReaderWriterCommon.h" static int panelHandle; static int readerChannel = 0; int CVICALLBACK UDPCallback (unsigned channel, int eventType, int errCode, void *callbackData); int main (int argc, char *argv[]) { int error = 0; if (InitCVIRTE (0, argv, 0) == 0) return -1; /* out of memory */ if ((panelHandle = LoadPanel (0, "UDPReader.uir", PANEL)) < 0) return -1; errChk (SetCtrlVal(panelHandle, PANEL_MULTICAST_IP, MULTICAST_ADDRESS)); errChk (CreateUDPChannelConfig(READER_PORT, UDP_ANY_ADDRESS, 0, UDPCallback, NULL, &readerChannel)); DisplayPanel (panelHandle); RunUserInterface (); DiscardPanel (panelHandle); Error: if (readerChannel) DisposeUDPChannel(readerChannel); if (error < 0) MessagePopup("Error", GetGeneralErrorString(error)); return 0; } int CVICALLBACK UDPCallback (unsigned channel, int eventType, int errCode, void *callbackData) { int error = 0, size; unsigned char *msg = NULL; if (eventType == UDP_DATAREADY) { char srcAddr[16]; unsigned int srcPort; char msgSourceString[16 + 10]; // Pass NULL as the input buffer to determine the size of the arrived data. errChk (size = UDPRead(channel, NULL, 0, UDP_DO_NOT_WAIT, NULL, NULL)); nullChk (msg = malloc(size)); // Read the waiting message into the allocated buffer. errChk (size = UDPRead(channel, msg, size, UDP_DO_NOT_WAIT, &srcPort, srcAddr)); // Display the message, preceeded by the sender's IP address and port number. sprintf(msgSourceString, "[%s:%d]: ", srcAddr, srcPort); errChk (SetCtrlVal(panelHandle, PANEL_TEXTBOX, msgSourceString)); errChk (SetCtrlVal(panelHandle, PANEL_TEXTBOX, msg)); errChk (SetCtrlVal(panelHandle, PANEL_TEXTBOX, "\n")); } Error: if (error < 0) MessagePopup("Error", GetGeneralErrorString(error));; if (msg) free(msg); return 0; } int CVICALLBACK DoMulticast (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { int error = 0; if (event == EVENT_COMMIT) { int on; char ipAddr[16]; errChk (GetCtrlVal(panel, control, &on)); errChk (GetCtrlVal(panel, PANEL_MULTICAST_IP, ipAddr)); if (on) errChk (UDPMulticastSubscribe(readerChannel, ipAddr, NULL)); else errChk (UDPMulticastUnsubscribe(readerChannel, ipAddr, NULL)); } Error: if (error < 0) MessagePopup("Error", GetGeneralErrorString(error)); return 0; } int CVICALLBACK PanelCallback (int panel, int event, void *callbackData, int eventData1, int eventData2) { if (event == EVENT_CLOSE) QuitUserInterface (0); return 0; }

UDP Writer #include <ansi_c.h> #include <cvirte.h> #include <userint.h> #include <udpsupp.h> #include "toolbox.h" #include "UDPWriter.h" #include "UDPReaderWriterCommon.h" #define MAX_DATA_INPUT_LENGTH 100 #define MAX_IP_INPUT_LENGTH 20 static int panelHandle; static int writerChannel = 0; int main (int argc, char *argv[]) { int error = 0; if (InitCVIRTE (0, argv, 0) == 0) return -1; /* out of memory */ if ((panelHandle = LoadPanel (0, "UDPWriter.uir", PANEL)) < 0) return -1; // Initialize some additional UI settings. errChk (SetCtrlAttribute(panelHandle, PANEL_DATA, ATTR_MAX_ENTRY_LENGTH, MAX_DATA_INPUT_LENGTH)); errChk (SetCtrlAttribute(panelHandle, PANEL_ADDR, ATTR_MAX_ENTRY_LENGTH, MAX_IP_INPUT_LENGTH)); // Create a UDP channel from which to send messages. The port number can be any available // port since we expect only to write, not receive data. errChk (CreateUDPChannel(UDP_ANY_LOCAL_PORT, &writerChannel)); DisplayPanel (panelHandle); RunUserInterface (); DiscardPanel (panelHandle); Error: if (writerChannel) DisposeUDPChannel(writerChannel); if (error < 0) MessagePopup("Error", GetGeneralErrorString(error)); return 0; } int CVICALLBACK Send (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { int error = 0; if (event == EVENT_COMMIT) { char data[MAX_DATA_INPUT_LENGTH + 1]; char destAddr[MAX_IP_INPUT_LENGTH + 1] = "0"; errChk (GetCtrlVal(panel, PANEL_DATA, data)); // Depending on which communication method is desired, the message is addressed to one of: // (1) a specific IP address or DNS-resolvable host name (Unicast), // errChk (GetCtrlVal(panel, PANEL_ADDR, destAddr)); // (2) a predetermined multicast address to which multiple readers may be subscribed (Multicast), // errChk (GetCtrlVal(panel, PANEL_ADDR, destAddr)); // (3) the broadcast address, which propogates to every computer on the subnet (Broadcast). // strcpy(destAddr, UDP_LAN_BROADCAST_ADDR); // Write the message to a predetermined port number on which all readers will listening. errChk (UDPWrite(writerChannel, READER_PORT, destAddr, data, strlen(data) + 1)); } Error: if (error < 0) MessagePopup("Error", GetGeneralErrorString(error)); return 0; } int CVICALLBACK PanelCallback (int panel, int event, void *callbackData, int eventData1, int eventData2) { if (event == EVENT_CLOSE) QuitUserInterface (0); return 0; }

Cliente

Servidor
CreateUDPChannelCon fig( porta local, endereo local, exclusividade, UDPCallback, ptr dado, &handle_canal) ON_CONNECT Notifica o Sistema Operacional que o programa atuar como Servidor e indica a funo que tratar os eventos de comunicao.

Pede conexo ao servidor recebendo do Sistema Operacional um handle para a conexo.

ConnectToTCPServer ( &h_conexo, porta, host, ptr Client_callback, ptr dado, timeout)

Recebe e trata os pedidos de conexo dos clientes. Associa um handle para cada conexo.

Processa a comunicao entre cliente e servidor usando o respectivo handle.

TCP_DATAREADY ClientTCPRead ( h_conexo, ptr buffer, tam dado, timeout)

UDPRead( canal, ptr buffer, tam buffer, timeout, ptr porta, ptr endereo)

Processa a comunicao entre servidor e cliente usando o respectivo handle.

Client_Callback TCP_DATAREADY TCP_DISCONNECT ClientTCPWrite ( h_conexo, ptr dado, tam dado , timeout)

Server_Callback ON_CONNECT TCP_DATAREADY ServerTCPRead ( h_conexo, ptr buffer, tam dado, timeout) TCP_DATAREADY TCP_DISCONNECT

Pede desconexo ao servidor liberando o respectivo handle.

DisconnectFromTCPServer ( h_conexo) TCP_DISCONNECT

Processa o pedido de desconexo do cliente liberando o respectivo handle.

Processa o aviso de desconexo enviado pelo servidor liberando o respectivo

DisconnectTCPClient ( h_conexo) TCP_DISCONNECT

Avisa ao cliente que ele ser desconectado e libera o respectivo handle.

DisposeUDPChannel( handle_canal)

Avisa ao Sistema Operacional que o programa est sendo encerrado.