3 * Copyright (c) 2002 - 2007, Blue Static <http://www.bluestatic.org>
5 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
6 * General Public License as published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
10 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public License along with this program; if not,
14 * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
17 #import "SocketWrapper.h"
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <netinet/in.h>
21 #include <arpa/inet.h>
24 NSString
*sockNotificationDebuggerConnection
= @
"debuggerconnection";
25 NSString
*sockDidAcceptNotification
= @
"socketdidaccept";
27 @implementation SocketWrapper
30 * Initializes the socket wrapper with a host and port
32 - (id)initWithPort
: (int)port
34 if (self = [super init
])
38 // the delegate notifications work funky because of threads. we register ourselves as the
39 // observer and then pass up the messages that are actually from this object (as we can't only observe self due to threads)
40 // to our delegate, and not to all delegates
41 [[NSNotificationCenter defaultCenter
] addObserver
: self selector
: @selector(_sendMessageToDelegate
:) name
: nil object
: nil];
47 * Close our socket and clean up anything else
57 * Returns the delegate
65 * Sets the delegate but does *not* retain it
67 - (void)setDelegate
: (id)delegate
73 * This is the notification listener for all types of notifications. If the notifications are from a SocketWrapper
74 * class, it checks that the value of _delegate in the NSNotification's userInfo matches that of this object. If it does,
75 * then the notification was sent from the same object in another thread and it passes the message along to the object's
76 * delegate. Complicated enough?
78 - (void)_sendMessageToDelegate
: (NSNotification
*)notif
80 // this isn't us, so there's no point in continuing
81 if ([[notif userInfo
] objectForKey
: sockNotificationDebuggerConnection
] != _delegate
)
86 NSString
*name
= [notif name
];
88 if (name
== sockDidAcceptNotification
)
90 [_delegate socketDidAccept
];
95 * Connects to a socket on the port specified during init. This will dispatch another thread to do the
96 * actual waiting. Delegate notifications are posted along the way to let the client know what is going on.
100 [NSThread detachNewThreadSelector
: @selector(_connect
:) toTarget
: self withObject
: nil];
104 * This does the actual dirty work (in a separate thread) of connecting to a socket
106 - (void)_connect
: (id)obj
108 NSAutoreleasePool
*pool
= [[NSAutoreleasePool alloc
] init
];
110 // create an INET socket that we'll be listen()ing on
111 int socketOpen
= socket(PF_INET
, SOCK_STREAM
, 0);
113 // create our address given the port
114 struct sockaddr_in address
;
115 address.sin_family
= AF_INET
;
116 address.sin_port
= htons(_port
);
117 address.sin_addr.s_addr
= htonl(INADDR_ANY
);
118 memset(address.sin_zero
, '\0', sizeof(address.sin_zero
));
120 // bind the socket... and don't give up until we've tried for a while
122 while (bind(socketOpen
, (struct sockaddr
*)&address
, sizeof(address
)) < 0)
127 [_delegate errorEncountered
: nil];
129 NSLog(@
"couldn't bind to the socket... trying again in 5");
134 // now we just have to keep our ears open
135 if (listen(socketOpen
, 0) == -1)
137 [_delegate errorEncountered
: nil];
140 // accept a connection
141 struct sockaddr_in remoteAddress
;
142 socklen_t remoteAddressLen
= sizeof(remoteAddress
);
143 _socket
= accept(socketOpen
, (struct sockaddr
*)&remoteAddress
, &remoteAddressLen
);
147 [_delegate errorEncountered
: nil];
150 // we're done listening now that we have a connection
153 [self _postNotification
: sockDidAcceptNotification withObject
: nil];
159 * Reads from the socket and returns the result as a NSString (because it's always going to be XML). Be aware
160 * that the underlying socket recv() call will *wait* for the server to send a message, so be sure that this
161 * is used either in a threaded environment so the interface does not hang, or when you *know* the server
162 * will return something (which we almost always do).
164 * Data string returned is autorelease'd
171 // do our initial recv() call to get (hopefully) all the data and the lengh of the packet
172 int recvd
= recv(_socket
, &buffer
, sizeof(buffer
), 0);
174 // take the received data and put it into an NSData
175 NSMutableData
*data
= [NSMutableData data
];
177 // strip the length from the packet, and clear the null byte then add it to the NSData
178 char packetLength
[8];
180 while (buffer
[i
] != '\0')
182 packetLength
[i
] = buffer
[i
];
186 // we also want the null byte, so move us up 1
189 // the total length of the full transmission
190 int length
= atoi(packetLength
);
192 // move the packet part of the received data into it's own char[]
193 char packet
[sizeof(buffer
)];
194 memmove(packet
, &buffer
[i
], recvd
- i
);
196 // convert bytes to NSData
197 [data appendBytes
: packet length
: recvd
];
199 // check if we have a partial packet
200 if (length
+ i
> sizeof(buffer
))
202 while (recvd
< length
)
204 int latest
= recv(_socket
, &buffer
, sizeof(buffer
), 0);
207 NSLog(@
"socket closed or error");
209 [data appendBytes
: buffer length
: latest
];
214 // convert the NSData into a NSString
215 [_delegate dataReceived
: [[[NSString alloc
] initWithData
: data encoding
: NSUTF8StringEncoding
] autorelease
]];
219 * Sends a given NSString over the socket
221 - (void)send
: (NSString
*)data
223 data
= [NSString stringWithFormat
: @
"%@\0", data
];
224 int sent
= send(_socket
, [data UTF8String
], [data length
], 0);
227 NSLog(@
"error in sending");
229 if (sent
< [data length
])
231 // TODO - do we really need to worry about partial sends with the lenght of our commands?
232 NSLog(@
"FAIL: only partial packet was sent; sent %d bytes", sent
);
235 [_delegate dataSent
];
239 * Helper method to simply post a notification to the default notification center with a given name and object
241 - (void)_postNotification
: (NSString
*)name withObject
: (id)obj
243 NSDictionary
*dict
= [NSDictionary dictionaryWithObjects
: [NSArray arrayWithObjects
: _delegate
, nil]
244 forKeys
: [NSArray arrayWithObjects
: sockNotificationDebuggerConnection
, nil]];
245 [[NSNotificationCenter defaultCenter
] postNotificationName
: name object
: obj userInfo
: dict
];