From a forum post: http://topic.csdn.net/u/20081231/06/6a1e156c-3015-4e93-9bcc-19ee2b32b13b.html
I modified the Code to facilitate testing.
1 server. Java Server
- Import java. Io. bufferedreader;
- Import java. Io. ioexception;
- Import java. Io. inputstreamreader;
- Import java. Io. printwriter;
- Import java.net. serversocket;
- Import java.net. Socket;
- Public class server {
- /**
- * @ Param ARGs
- * The command line arguments
- */
- Public static void main (string [] ARGs) throws ioexception {
- String data = "toobie ornaught toobie ";
- Try {
- Serversocket srvr = new serversocket (8085 );
- Socket SKT = srvr. Accept ();
- System. Out. Print ("server has connected! /N ");
- Bufferedreader in = new bufferedreader (New inputstreamreader (SKT
- . Getinputstream ()));
- Printwriter out = new printwriter (SKT. getoutputstream (), true );
- System. Out. Print ("sending string: '" + Data + "'/N ");
- Out. print (data ); // ############ the problem appears here ##################
- System. Out. Print ("sending string: '" + Data + "'/N ");
- While (! In. Ready ()){
- }
- System. Out. println (in. Readline ());
- Out. Close ();
- In. Close ();
- SKT. Close ();
- Srvr. Close ();
- } Catch (exception e ){
- System. Out. Print ("whoops! It didn't work! /N ");
- }
- }
- }
2 client. Java client
- Import java. Io. bufferedreader;
- Import java. Io. ioexception;
- Import java. Io. inputstreamreader;
- Import java. Io. printwriter;
- Import java.net. Socket;
- Public class client {
- /**
- * @ Param ARGs
- * The command line arguments
- */
- Public static void main (string [] ARGs) throws ioexception {
- Try {
- Socket SKT = new socket ("localhost", 8085 );
- Bufferedreader in = new bufferedreader (New inputstreamreader (SKT
- . Getinputstream ()));
- Printwriter out = new printwriter (SKT. getoutputstream (), true );
- String inputline, outputline;
- While (! In. Ready ()){
- }
- System. Out. println (in. Readline ());
- Out. Print ("AAA ");
- Out. Close ();
- In. Close ();
- SKT. Close ();
- } Catch (exception e ){
- System. Out. Print ("whoops! It didn't work! /N ");
- }
- }
- }
After the system is running, the system stops responding and is waiting. After checking, the out. Print is the root of the problem.
Change
Out. println (data );
You can:
The reason is that Readline is used, and this is only two possibilities that will continue.
1 encountered a line break
2. The end of the data
And you only sent
Out. Print (data );
The opposite side does not know that you have sent the data, so keep waiting for your line feed ....
Of course, this problem will not occur if you use read to read bytes instead of Readline on the client. This is also the special feature of Readline.