我必须使用套接字编程为iOS创建一个聊天应用程序,我的IP地址为192.168.0.57:9300
。 我已经使用了Raywenderlich
套接字编程示例,接收数据正常工作但发送不工作,没有任何错误或崩溃。 我的代码如下。开如何使用NSOutputStream通过套接字发送NSString
码流
- (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];
}
请给我提供建议。
你是什么意思,“它显示发送字符串”?接收机是否显示它?什么是接收器(什么软件,如果可能,发布源代码片段)?你如何处理收到的字符串? – nullp01nter
我已附加所有code.server代码都是用php编写的 – Suraj
我用你的确切代码来初始化一个连接并将网络流量从iPhone发送到我的Mac。接收软件是用Objective C编写的,也使用NSStream。所有传输的字符串都可以。我想你的问题可能在服务器端(PHP)。你能否验证(用另一个软件发送字符串)你的服务器部分正在工作? – nullp01nter