I’m trying to create a simple chat application for iOS. It works for receiving messages, but not for sending messages. I use Ruby and a TCPServer as the chat server (as of: twgr), it looks like this:
require 'socket'
server = TCPServer.new("localhost", 80)
chatters = []
def welcome(chatter)
chatter.puts "Welcome Chatter!"
end
def broadcast(message, chatters)
chatters.each do |chatter|
chatter.puts message
end
end
while (chatter = server.accept)
Thread.new(chatter) do |c|
welcome(chatter)
chatters << chatter
begin
loop do
line = c.readline
broadcast("#{line}", chatters)
end
rescue EOFError
c.close
chatters.delete(c)
broadcast("Chatter has left", chatters)
end
end
end
The server seems to be working ok, since I can send messages between two local telnet connections. I think the problem is my iOS client. The code I use for sending/reciving messages looks like this (as of:http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server):
- (void)messageReceived:(NSString *)message
{
[messages insertObject:message atIndex:0];
NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationTop];
[self.tableView endUpdates];
}
/*
Method for creating messages.
New messages are added above older messages.
It gets called when the user hits the "Send" button.
*/
- (IBAction)sendMessage:(id)sender {
NSString *response = [NSString stringWithFormat:messageField.text];
NSData *data = [[NSData alloc] initWithData:[response
dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
messageField.text = @"";
}
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
switch (streamEvent) {
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
// This NSLog message dosn't get called when I want to send messages from
// my iOS client.
NSLog(@"Hello");
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer
length:len
encoding:NSASCIIStringEncoding];
if (nil != output) {
NSLog(@"server said: %@", output);
[self messageReceived:output];
}
}
}
}
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
break;
}
}
I can receive messages on the iOS client when I send messages but nothing happens when I try to send messages. The client currently looks like this:

This was a though nut to crack, but I think that I solved it (the trial and error way). The message receiving part seemed to work because Ruby’s puts method automatically adds a newline to the strings, which is not the case for NSStrings. This change made it work: