Iphone NSStreamDelegate问题连接到Java套接字服务器

时间:2012-08-23 01:56:52

标签: iphone sockets

我正在尝试从我的iphone模拟器打开套接字连接,并将一个简单的NSString发送到我在端口80中使用java设置的本地主机服务器。

我遇到的问题是,当我在NSOutputStream上写入数据时,在关闭模拟器之前服务器没有接收到它。然后服务器接收数据并抛出此异常java.net.SocketException:Broken pipe

我知道与关闭NSOutputStream和刷新有关,但我怎样才能在Objective c中实现这一点?

我在我的初始ViewController中调用ProtocolCommunication,如下所示:

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

ProtocolCommunication class(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 Server

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

任何想法?

1 个答案:

答案 0 :(得分:0)

我只需将NS添加到NSString就解决了这个问题:

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