0

iphoneシミュレーターからソケット接続を開こうとしていて、単純なNSStringをポート80のJavaでセットアップしたローカルホストサーバーに送信しようとしています。

私が抱えている問題は、NSOutputStream にデータを書き込むと、シミュレーターを閉じるまでサーバーに受信されないことです。そして、サーバーがデータを受信すると、この例外がスローされます java.net.SocketException: Broken pipe

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

何か案は??

4

1 に答える 1

0

次のように NSString に \n を追加するだけで解決しました。

NSString *response  = @"HELLO from my iphone \n"; // This flushes the NSOutputStream so becarefull everyone
于 2012-08-23T02:14:07.300 に答える