0

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

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

我知道与关闭 NSOutputStream 和刷新有关,但是如何在 Objective c 中实现这一点?

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

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

协议通信类 (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

我通过像这样将 \n 添加到 NSString 来解决它:

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