2 * WINGs connect.c: example how to create a network client using WMConnection
4 * Copyright (c) 1999-2002 Dan Pascu
13 #include <WINGs/WINGs.h>
17 static int initialized
= 0;
21 static void didReceiveInput(ConnectionDelegate
*self
, WMConnection
*cPtr
);
23 static void connectionDidDie(ConnectionDelegate
*self
, WMConnection
*cPtr
);
25 static void didInitialize(ConnectionDelegate
*self
, WMConnection
*cPtr
);
29 static ConnectionDelegate socketDelegate
= {
31 NULL
, /* canResumeSending */
32 NULL
, /* didCatchException */
33 connectionDidDie
, /* didDie */
34 didInitialize
, /* didInitialize */
35 didReceiveInput
, /* didReceiveInput */
49 getMessage(WMConnection
*cPtr
)
55 aData
= WMGetConnectionAvailableData(cPtr
);
58 if ((length
=WMGetDataLength(aData
))==0) {
63 buffer
= (char*)wmalloc(length
+1);
64 WMGetDataBytes(aData
, buffer
);
73 inputHandler(int fd
, int mask
, void *clientData
)
75 WMConnection
*cPtr
= (WMConnection
*)clientData
;
83 n
= read(fd
, buf
, 4096);
85 aData
= WMCreateDataWithBytes(buf
, n
);
86 WMSendConnectionData(cPtr
, aData
);
93 didReceiveInput(ConnectionDelegate
*self
, WMConnection
*cPtr
)
97 buffer
= getMessage(cPtr
);
99 fprintf(stderr
, "Connection closed by peer.\n");
103 printf("%s", buffer
);
110 connectionDidDie(ConnectionDelegate
*self
, WMConnection
*cPtr
)
112 WMCloseConnection(cPtr
);
114 fprintf(stderr
, "Connection closed by peer.\n");
120 didInitialize(ConnectionDelegate
*self
, WMConnection
*cPtr
)
122 int state
= WMGetConnectionState(cPtr
);
125 if (state
== WCConnected
) {
126 host
= WMGetHostWithAddress(WMGetConnectionAddress(cPtr
));
127 fprintf(stderr
, "connected to '%s:%s'\n",
128 host
?WMGetHostName(host
):WMGetConnectionAddress(cPtr
),
129 WMGetConnectionService(cPtr
));
135 wsyserrorwithcode(WCErrorCode
, "Unable to connect");
142 main(int argc
, char **argv
)
144 char *ProgName
, *host
, *port
;
150 WMInitializeApplication("connect", &argc
, argv
);
152 ProgName
= strrchr(argv
[0],'/');
162 for (i
=1; i
<argc
; i
++) {
163 if (strcmp(argv
[i
], "--help")==0 || strcmp(argv
[i
], "-h")==0) {
164 printf("usage: %s [host [port]]\n\n", ProgName
);
175 printf("Trying to make connection to '%s:%s'\n",
176 host
?host
:"localhost", port
);
178 sPtr
= WMCreateConnectionToAddressAndNotify(host
, port
, NULL
);
180 wfatal("could not create connection. exiting");
184 WMSetConnectionDelegate(sPtr
, &socketDelegate
);
186 /* watch what user types and send it over the connection */
187 WMAddInputHandler(0, WIReadMask
, inputHandler
, sPtr
);