SOURCE program:
Client:
Class Tcpclient4{public static void Main (string[] args) {Socket s=null;//is defined outside the block, otherwise it cannot be found in the catch! -------> Initialize, otherwise finally in the judgment when you are prompted you may not have initialized!! Try{s=new Socket ("127.0.0.1", 10013);//single try, not even directly terminate the run, do not continue to run the following program is necessary! try{//tested, according to the default encoding Notepad save, here only with UTF-8 decoding copy result is garbled! Press Utf-8 to save, the copy result is still inconsistent (the number of bytes is inconsistent!) ), but not garbled! (One more?) Here's the test: where Sscc.txt is the Utf-8 file, the text: "Did your mom force you to get married?" "30 bytes. Deliberately with gb2312 decoding, the result of course garbled: Byte, the content is inconsistent, but here according to Utf-8 Normal decoding, the following all default, then not garbled, the front more a?, and the number of bytes is inconsistent, the display is 21 bytes, the description is GBK or GB2312 encoding! BufferedReader bufr=new BufferedReader (New InputStreamReader (New FileInputStream ("C:\\sscc.txt"), "UTF8");// The bottom is read bytes, here you can specify the code table, and is converted into a character stream reading mode//bufferedreader bufr=new BufferedReader (New FileReader ("C:\\x.txt");// This is the default encoding gbkprintwriter pw=new PrintWriter (S.getoutputstream (), true);//The second parameter is true: Automatically refreshes the string Line=null;while ((line= Bufr.readline ())!=null) {pw.println (line);//auto-add carriage return, over there readLine can determine and successfully read a row}}catch (Exception ex) {throw new RuntimeException (ex);}} catch (Exception e) {throw new RuntimeException (e);} FINALLY{TRY{//S is a reference if (S!=null) S.close ();} catch (Exception exc) {throW New RuntimeException (EXC);}}}
Server:
Class tcpserver4{public static void Main (string[] args) {ServerSocket ss=null;//to be defined outside the block, otherwise the catch cannot be found! Socket s=null;try{ss=new ServerSocket (10013); s=ss.accept (); Try{bufferedreader bufr=new BufferedReader (new InputStreamReader (S.getinputstream ())); PrintWriter pw=new PrintWriter (New FileWriter ("C:\\x2.txt"), true); String Line=null;while ((Line=bufr.readline ())!=null) {pw.println (line);}} catch (Exception ex) {throw new RuntimeException (ex);}} catch (Exception e) {throw new RuntimeException (e);} Finally{try{if (S!=null) s.close (); if (ss!=null) Ss.close ();} catch (Exception exc) {throw new runtimeexception (exc);}}}
about exception handling:
1.Socket related to separate try processing, connection problems will not continue to run the following code is necessary;
2.Socket (reference) is defined outside the try block, otherwise the catch block cannot be found!
3.Socket needs to be initialized at the time of definition, otherwise the compile hint: if judgment in finally can be the case that the socket has not been initialized!
Results copied by different code tables:
Test verification: According to the default ANSI encoding Notepad save, the program in accordance with the default Code table processing, normal replication, the results of the content and bytes are consistent with the source file, no problem: ANSI corresponding to the Chinese code GBK, and FileReader, FileWriter, such as the default Code table is also GBK, not garbled
According to UTF-8 Save the text (can be seen from the number of bytes, UTF-8 a Chinese character 3 bytes), the client reads in accordance with UTF-8 normal decoding (decoding the Chinese character string), all other places by default encoding, the result is not garbled, but the text at the beginning of an inexplicable more?
Conclusion: Some reasons are unknown, can only see the actual results, not subjective speculation, take it for granted! Actual programming as long as strictly according to the same Code table encoding and decoding will not be the problem! Seize this, everything else do not delve into, do not venture to try!!!
Program improvement of feedback information after uploading successfully:
Note that at the end of the client's while loop (it can be finished, read the file), if there is no additional end tag, then there is a blocking readline waiting for feedback, and the end of the service side is blocked if it does not get the closing tag.
Client:
Class Tcpclient4{public static void Main (string[] args) {Socket s=null;//is defined outside the block, otherwise it cannot be found in the catch! -------> Initialize, otherwise finally in the judgment when you are prompted you may not have initialized!! Try{s=new Socket ("127.0.0.1", 10013);//single try, not even directly terminate the run, do not continue to run the following program is necessary! Try{bufferedreader bufr=new BufferedReader (New InputStreamReader (New FileInputStream ("C:\\xxcc.txt"), "GBK");// BufferedReader bufr=new BufferedReader (New FileReader ("C:\\x.txt")); PrintWriter pw=new PrintWriter (S.getoutputstream (), true);//second parameter true: automatically refreshes the string Line=null;while ((line= Bufr.readline ())!=null) {pw.println (line);//auto-add carriage return, over there readLine can judge and successfully read a row}//can define the end tag over there judgment (read, pass over, over there to get after judgment, Using DataOutputStream), such as the empty line (Tomcat's approach, splitting the header and body of the request and response) and the timestamp (Long integer, DataInputStream Readlong method), Here the method of calling the socket closes the output stream s.shutdownoutput ();//close the output stream of the client, which is equivalent to adding an end tag to the stream-1, let the loop over there stop/read an upload successful feedback BufferedReader bufin= New BufferedReader (New InputStreamReader (S.getinputstream ())); String str=bufin.readline ();//Need newline character System.out.println (str), Bufr.close () s.close ();//socket-related stream closes naturally with socket closed }catch (Exception ex) {throw new RuntimeexceptioN (ex);}} catch (Exception e) {throw new RuntimeException (e);} FINALLY{TRY{//S is a reference if (S!=null) S.close ();} catch (Exception exc) {throw new runtimeexception (exc);}}}
Server:
Class tcpserver4{public static void Main (string[] args) {ServerSocket ss=null;//to be defined outside the block, otherwise the catch cannot be found! Socket s=null;try{ss=new ServerSocket (10013); s=ss.accept (); Try{bufferedreader bufr=new BufferedReader (new InputStreamReader (S.getinputstream ())); PrintWriter pw=new PrintWriter (New FileWriter ("C:\\x2.txt"), true); String Line=null;while ((Line=bufr.readline ())!=null) {pw.println (line);} That way, the socket output stream is closed to end the loop here, so this can still be called, is it re-opened? PrintWriter pout=new PrintWriter (S.getoutputstream (), True);p out.println ("Upload succeed."); /must have a carriage return to the line, over there to Readlinepw.close ();//socket-related stream closed with the socket closed naturally! }catch (Exception ex) {throw new RuntimeException (ex);}} catch (Exception e) {throw new RuntimeException (e);} Finally{try{if (S!=null) s.close (); if (ss!=null) Ss.close ();} catch (Exception exc) {throw new runtimeexception (exc);}}}
The file was successfully copied and the test was successful. Client results:
D:\java\practice3>java TcpClient4
Upload succeed.
D:\java\practice3>
[Java] A TCP text upload-related exception handling and accidental derivation of Chinese coding problems