gpt4 book ai didi

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

转载 作者:技术小花猫 更新时间:2023-10-29 11:22:38 32 4
gpt4 key购买 nike

我必须使用套接字编程为 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];

}

请给我建议。

最佳答案

您应该像这样在回复末尾添加“\n”:

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

这对我有用,但我的问题是我无法使用函数 (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent 接收数据

关于iphone - 如何使用 NSOutputStream 通过套接字发送 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12817877/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com