2012-08-23 66 views
0

我试图打开从我的iPhone模拟器一个套接字连接,并发送一个简单的NSString我在端口设置与Java 80连接到Java socket服务器iPhone NSStreamDelegate问题

,我有一个问题,本地主机服务器当我在NSOutputStream上写入数据时,服务器没有收到它,直到关闭模拟器。然后服务器接收到数据,并引发这个异常java.net.SocketException:损坏的管道

我知道是关闭NSOutputStream和刷新相关的东西,但我怎么能在Objective C中实现这一点?

我这样调用在我最初的ViewController的ProtocolCommunication:

protocol = [[ProtocolCommunication alloc] init]; 
    [protocol initNetworkCommunication]; 
    [protocol sendData]; 

ProtocolCommunication类(IOS)

@implementation ProtocolCommunication 
@synthesize inputStream, outputStream 

- (void) initNetworkCommunication { 

CFReadStreamRef readStream; 
CFWriteStreamRef writeStream; 
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", 80, &readStream, &writeStream); 
inputStream = (NSInputStream *)readStream; 
outputStream = (NSOutputStream *)writeStream; 
[inputStream setDelegate:self]; 
[outputStream setDelegate:self]; 
//do the Looping 
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
[inputStream open]; 
[outputStream open]; 
NSLog(@"INIT COMPLETE"); 

} 

- (void) sendData { 

NSString *response = @"HELLO from my iphone"; 
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]]; 
[outputStream write:[data bytes] maxLength:[data length]]; 

} 

Java服务器

String msgReceived;  
    try { 
     ServerSocket serverSocket = new ServerSocket(80); 
     System.out.println("RUNNING SERVER"); 
     while (running) { 
      Socket connectionSocket = serverSocket.accept(); 
      BufferedReader inFromClient = new BufferedReader(
        new InputStreamReader(connectionSocket.getInputStream())); 
      DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); 
      msgReceived = inFromClient.readLine(); 
      System.out.println("Received: " + msgReceived);    
      outToClient.writeBytes("Aloha from server"); 
      outToClient.flush(); 
      outToClient.close(); 
     } 

    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

任何想法?

回答

0

我解决它只需添加\ n向的NSString这样的:

NSString *response = @"HELLO from my iphone \n"; // This flushes the NSOutputStream so becarefull everyone