简体   繁体   English

如何使用NSOutputStream通过套接字发送NSString

[英]How to send NSString through socket using NSOutputStream

I have to create a chat app for iOS using socket programming and my IP address is 192.168.0.57:9300 . 我必须使用套接字编程为iOS创建一个聊天应用程序,我的IP地址是192.168.0.57:9300 I have used Raywenderlich socket programming example,receiving data working properly but sending not working ,there are no any error or crash. 我使用了Raywenderlich套接字编程示例,接收数据正常工作但发送不工作,没有任何错误或崩溃。 My code are as follows. 我的代码如下。

code for opening streams 打开流的代码

- (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];    
}

code for sending data 发送数据的代码

- (IBAction)sendMessage:(id)sender
{
        NSString *response  = @"lets start chat";
        NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
        [outputStream write:[data bytes] maxLength:[data length]]; 
}

Delegates 代表

- (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];

    }

please provide me suggestion. 请给我一些建议。

You should add the "\\n" at the end of your response like this: 您应该在响应的末尾添加“\\ n”,如下所示:

- (IBAction)sendMessage:(id)sender
{
        NSString *response  = @"lets start chat\n";
        ////your code
}

This work for me, but my problem is that I cannot receive data using the function (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent 这对我有用,但我的问题是我无法使用函数(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent接收数据(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent

I had similar problem. 我有类似的问题。 Got it solved by appending new-line and line-feed character in string. 通过在字符串中添加换行符和换行符来解决它。

- (IBAction)sendMessage:(id)sender {

        NSString *response  = @"lets start chat\r\n\r\n";
        NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
        [outputStream write:[data bytes] maxLength:[data length]]; 
}

I found writing a separate thread solved this issue for me. 我发现写一个单独的线程为我解决了这个问题。
Makes sense as one shouldn't really do network ops on the main thread. 有道理,因为不应该在主线程上真正做网络操作。
Here is my code: 这是我的代码:

dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^(void) {
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
    NSInteger len = [outputStream write:[data bytes] maxLength:[data length]];
    NSLog(@"Len = %ld", len);
});

Another point to note is that the NSStreamEventOpenCompleted event is called twice. 另一点需要注意的是,NSStreamEventOpenCompleted事件被调用两次。 Once when each of the input and output streams are opened. 一旦打开每个输入和输出流。 So one needs to be careful not to write to the output stream prior to its event. 因此,需要注意不要在事件发生之前写入输出流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM