[英]iOS Hello World over socket
I need to implement simple socket communication (strings) between iOS app and my Java socket server. 我需要在iOS应用程序和我的Java套接字服务器之间实现简单的套接字通信(字符串)。 I manage to connect the two, but I cannot send any messages.
我设法连接这两个,但我不能发送任何消息。 Java server is pretty much taken from this example , and this is part of my code where I establish connection and (try to) send message to server:
Java服务器几乎取自这个例子 ,这是我建立连接和(尝试)向服务器发送消息的代码的一部分:
- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.10", 2004, &readStream, &writeStream);
self.inputStream = objc_unretainedObject(readStream);
self.outputStream = objc_unretainedObject(writeStream);
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[self.outputStream open];
}
- (void)sendMessage {
NSString *response = [NSString stringWithFormat:@"aaa"];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[self.outputStream write:[data bytes] maxLength:[data length]];
}
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSLog(@"stream event %i", streamEvent);
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == self.inputStream) {
uint8_t buffer[1024];
int len;
while ([self.inputStream hasBytesAvailable]) {
len = [self.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 NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
theStream = nil;
break;
default:
NSLog(@"Unknown event");
}
}
- (IBAction)loginButtonClicked {
[self initNetworkCommunication];
[self sendMessage];
...}
Too late for a reply.. Hope this helps someone... 答复太迟了..希望这有助于某人......
To send a String over Sockets, you must mark the end of the string. 要通过套接字发送字符串,必须标记字符串的结尾。 ie;
即; Add a \\n
添加\\ n
For the above example : 对于上面的例子:
Method : sendMessage 方法: sendMessage
NSString *response = [NSString stringWithFormat:@"aaa\n"];
Better to add something that can't be typed - eg, 0x00 - at the end. 最好添加一些无法输入的内容 - 例如,0x00 - 。 That way your message can contain anything.
这样你的消息可以包含任何东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.