ServerSocket java not reading inputStream?

后端 未结 3 1990
小蘑菇
小蘑菇 2021-01-27 13:06

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

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

        while (true) 
        { 
         


        
相关标签:
3条回答
  • 2021-01-27 13:48

    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.

    0 讨论(0)
  • 2021-01-27 13:59

    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.

    0 讨论(0)
  • 2021-01-27 14:09

    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 讨论(0)
提交回复
热议问题