开发者

ServerSocket java not reading inputStream?

I have written a server is java here is the code:

public mainClass() 
{ 
    try 
    { 
        ss = new ServerSocket(8080); 

        while (true) 
        { 
            socket = ss.accept(); 
            System.out.println("It is accept!");

            in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
            //out = new PrintWriter(socket.getOutputStream(),true); 

            line = in.readLine(); 
            System.out.println("you input is :" + line); 
            //out.close(); 
            in.close(); 
            socket.close();

        } 

    } 
    catch (IOException e) 
    {

    }

and I am using an iPhone application as the client. now what my problem is that the server is not reading the inputstream while the appication is running on the iphone.. But as soon as the application is terminated the java program prints out the String which has been sent to the server..Not sure what is happening here..sorry if this is not a good question..

- (void)viewDidLoad {
[super viewDidLoad];

socket = [[LXSocket alloc]开发者_Go百科init];

if ([socket connect:@"10.211.55.2" port:8080]) {

    NSLog(@"socket has been created");
}
else {
    NSLog(@"socket couldn't be created created");
}

@try {

[socket sendString:@"Hi This is a second test"];
}

@catch (NSException * e) {
NSLog(@"Unable to send data");
}


    [super viewDidLoad];

}

thanks, TC


From my own experience, readLine is not a good idea, especially when working with different languages and platforms, a better approach will be to use InputStreamReader and its read(char[] buff) method, and agree on both sides regarding the length to be sent each time.

Again, I have no reference to that, only my experience.

Also, looking at your code, you send a string without a new line character: [socket sendString:@"Hi This is a second test"]; maybe adding \n at the end will solve it for you.


My guess is that the client application doesn't send any line break at the end of the string it sends. So BufferedReader.readLine() waits for an EOL character, and only returns the string when the client application ends, because at this point the connection is closed and the reader knows there won't ever be an EOL, and the string is the last line it will ever receive.


BufferedReader can be dangerous; the buffering can cause short lines to get "stuck" if you're only reading a little data at a time, or if the data is coming across a network. If you're only using BufferedReader to get readLine(), then do this:

new BufferedReader(new InputStreamReader(socket.getInputStream()), 1);

That extra argument sets the buffer size to 1 character, effectively turning it off. That generally solves this kind of problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜