2 * WINGs connect.c: example how to create a network client using WMConnection
4 * Copyright (c) 1999-2003 Dan Pascu
13 #include <WINGs/WINGs.h>
15 static int initialized = 0;
17 static void didReceiveInput(ConnectionDelegate * self, WMConnection * cPtr);
19 static void connectionDidDie(ConnectionDelegate * self, WMConnection * cPtr);
21 static void didInitialize(ConnectionDelegate * self, WMConnection * cPtr);
23 static ConnectionDelegate socketDelegate = {
25 NULL, /* canResumeSending */
26 NULL, /* didCatchException */
27 connectionDidDie, /* didDie */
28 didInitialize, /* didInitialize */
29 didReceiveInput, /* didReceiveInput */
38 static char *getMessage(WMConnection * cPtr)
44 aData = WMGetConnectionAvailableData(cPtr);
47 if ((length = WMGetDataLength(aData)) == 0) {
52 buffer = (char *)wmalloc(length + 1);
53 WMGetDataBytes(aData, buffer);
54 buffer[length] = '\0';
60 static void inputHandler(int fd, int mask, void *clientData)
62 WMConnection *cPtr = (WMConnection *) clientData;
70 n = read(fd, buf, 4096);
72 aData = WMCreateDataWithBytes(buf, n);
73 WMSendConnectionData(cPtr, aData);
78 static void didReceiveInput(ConnectionDelegate * self, WMConnection * cPtr)
82 buffer = getMessage(cPtr);
84 fprintf(stderr, "Connection closed by peer.\n");
93 static void connectionDidDie(ConnectionDelegate * self, WMConnection * cPtr)
95 WMCloseConnection(cPtr);
97 fprintf(stderr, "Connection closed by peer.\n");
101 static void didInitialize(ConnectionDelegate * self, WMConnection * cPtr)
103 int state = WMGetConnectionState(cPtr);
106 if (state == WCConnected) {
107 host = WMGetHostWithAddress(WMGetConnectionAddress(cPtr));
108 fprintf(stderr, "connected to '%s:%s'\n",
109 host ? WMGetHostName(host) : WMGetConnectionAddress(cPtr), WMGetConnectionService(cPtr));
115 wsyserrorwithcode(WCErrorCode, "Unable to connect");
120 int main(int argc, char **argv)
122 char *ProgName, *host, *port;
128 WMInitializeApplication("connect", &argc, argv);
130 ProgName = strrchr(argv[0], '/');
140 for (i = 1; i < argc; i++) {
141 if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
142 printf("usage: %s [host [port]]\n\n", ProgName);
153 printf("Trying to make connection to '%s:%s'\n", host ? host : "localhost", port);
155 sPtr = WMCreateConnectionToAddressAndNotify(host, port, NULL);
157 wfatal("could not create connection. exiting");
161 WMSetConnectionDelegate(sPtr, &socketDelegate);
163 /* watch what user types and send it over the connection */
164 WMAddInputHandler(0, WIReadMask, inputHandler, sPtr);