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();
}
任何想法?