2 * WINGs connect.c: example how to create a network client using WMConnection
4 * Copyright (c) 1999-2001 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
, /* didCatchException */
32 connectionDidDie
, /* didDie */
33 didInitialize
, /* didInitialize */
34 didReceiveInput
, /* didReceiveInput */
41 wAbort(Bool foo
) /*FOLD00*/
48 getMessage(WMConnection
*cPtr
)
54 aData
= WMGetConnectionAvailableData(cPtr
);
57 if ((length
=WMGetDataLength(aData
))==0) {
62 buffer
= (char*)wmalloc(length
+1);
63 WMGetDataBytes(aData
, buffer
);
72 inputHandler(int fd
, int mask
, void *clientData
)
74 WMConnection
*cPtr
= (WMConnection
*)clientData
;
82 n
= read(fd
, buf
, 4096);
84 aData
= WMCreateDataWithBytes(buf
, n
);
85 WMSendConnectionData(cPtr
, aData
);
92 didReceiveInput(ConnectionDelegate
*self
, WMConnection
*cPtr
) /*FOLD00*/
96 buffer
= getMessage(cPtr
);
98 fprintf(stderr
, "Connection closed by peer.\n");
102 printf("%s", buffer
);
109 connectionDidDie(ConnectionDelegate
*self
, WMConnection
*cPtr
) /*FOLD00*/
111 WMCloseConnection(cPtr
);
113 fprintf(stderr
, "Connection closed by peer.\n");
119 didInitialize(ConnectionDelegate
*self
, WMConnection
*cPtr
)
121 int state
= WMGetConnectionState(cPtr
);
124 if (state
== WCConnected
) {
125 host
= WMGetHostWithAddress(WMGetConnectionAddress(cPtr
));
126 fprintf(stderr
, "connected to '%s:%s'\n",
127 host
?WMGetHostName(host
):WMGetConnectionAddress(cPtr
),
128 WMGetConnectionService(cPtr
));
134 wsyserrorwithcode(WCErrorCode
, "Unable to connect");
141 main(int argc
, char **argv
) /*FOLD00*/
143 char *ProgName
, *host
, *port
;
149 WMInitializeApplication("connect", &argc
, argv
);
151 ProgName
= strrchr(argv
[0],'/');
161 for (i
=1; i
<argc
; i
++) {
162 if (strcmp(argv
[i
], "--help")==0 || strcmp(argv
[i
], "-h")==0) {
163 printf("usage: %s [host [port]]\n\n", ProgName
);
174 printf("Trying to make connection to '%s:%s'\n",
175 host
?host
:"localhost", port
);
177 sPtr
= WMCreateConnectionToAddressAndNotify(host
, port
, NULL
);
179 wfatal("could not create connection. exiting");
183 WMSetConnectionDelegate(sPtr
, &socketDelegate
);
185 /* watch what user types and send it over the connection */
186 WMAddInputHandler(0, WIReadMask
, inputHandler
, sPtr
);