2
* WINGs connect.c: example how to create a network client using WMConnection
4
* Copyright (c) 1999-2003 Dan Pascu
14
#include <WINGs/WINGs.h>
18
static int initialized = 0;
22
static void didReceiveInput(ConnectionDelegate *self, WMConnection *cPtr);
24
static void connectionDidDie(ConnectionDelegate *self, WMConnection *cPtr);
26
static void didInitialize(ConnectionDelegate *self, WMConnection *cPtr);
30
static ConnectionDelegate socketDelegate = {
32
NULL, /* canResumeSending */
33
NULL, /* didCatchException */
34
connectionDidDie, /* didDie */
35
didInitialize, /* didInitialize */
36
didReceiveInput, /* didReceiveInput */
50
getMessage(WMConnection *cPtr)
56
aData = WMGetConnectionAvailableData(cPtr);
59
if ((length=WMGetDataLength(aData))==0) {
64
buffer = (char*)wmalloc(length+1);
65
WMGetDataBytes(aData, buffer);
74
inputHandler(int fd, int mask, void *clientData)
76
WMConnection *cPtr = (WMConnection*)clientData;
84
n = read(fd, buf, 4096);
86
aData = WMCreateDataWithBytes(buf, n);
87
WMSendConnectionData(cPtr, aData);
94
didReceiveInput(ConnectionDelegate *self, WMConnection *cPtr)
98
buffer = getMessage(cPtr);
100
fprintf(stderr, "Connection closed by peer.\n");
104
printf("%s", buffer);
111
connectionDidDie(ConnectionDelegate *self, WMConnection *cPtr)
113
WMCloseConnection(cPtr);
115
fprintf(stderr, "Connection closed by peer.\n");
121
didInitialize(ConnectionDelegate *self, WMConnection *cPtr)
123
int state = WMGetConnectionState(cPtr);
126
if (state == WCConnected) {
127
host = WMGetHostWithAddress(WMGetConnectionAddress(cPtr));
128
fprintf(stderr, "connected to '%s:%s'\n",
129
host?WMGetHostName(host):WMGetConnectionAddress(cPtr),
130
WMGetConnectionService(cPtr));
136
wsyserrorwithcode(WCErrorCode, "Unable to connect");
143
main(int argc, char **argv)
145
char *ProgName, *host, *port;
151
WMInitializeApplication("connect", &argc, argv);
153
ProgName = strrchr(argv[0],'/');
163
for (i=1; i<argc; i++) {
164
if (strcmp(argv[i], "--help")==0 || strcmp(argv[i], "-h")==0) {
165
printf("usage: %s [host [port]]\n\n", ProgName);
176
printf("Trying to make connection to '%s:%s'\n",
177
host?host:"localhost", port);
179
sPtr = WMCreateConnectionToAddressAndNotify(host, port, NULL);
181
wfatal("could not create connection. exiting");
185
WMSetConnectionDelegate(sPtr, &socketDelegate);
187
/* watch what user types and send it over the connection */
188
WMAddInputHandler(0, WIReadMask, inputHandler, sPtr);