ソケット プログラミングを使用して iOS 用のチャット アプリを作成する必要があり、私の IP アドレスは192.168.0.57:9300
. ソケット プログラミングの例を使用Raywenderlich
しました。データは正しく受信されますが、送信は機能しません。エラーやクラッシュはありません。私のコードは次のとおりです。
ストリームを開くためのコード
- (void) initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.57", 9300, &readStream, &writeStream);
inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
データ送信用コード
- (IBAction)sendMessage:(id)sender
{
NSString *response = @"lets start chat";
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[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 == inputStream) {
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(@"\nreciving data------%@,buffer);
[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 release];
theStream = nil;
break;
default:
NSLog(@"Unknown event");
}
}
Message sending
- (void) messageReceived:(NSString *)message {
[self.messages addObject:message];
[self.tView reloadData];
NSIndexPath *topIndexPath = [NSIndexPath indexPathForRow:messages.count-1
inSection:0];
[self.tView scrollToRowAtIndexPath:topIndexPath
atScrollPosition:UITableViewScrollPositionMiddle
animated:YES];
}
私に提案をしてください。