1. 程式人生 > >使用socket 通訊 解決傳輸亂碼的問題。

使用socket 通訊 解決傳輸亂碼的問題。

                String localChartSet = System.getProperty("file.encoding");
                System.out.println("localChartSet>>>>"+localChartSet);
                // 讀取客戶端資料
                DataInputStream input = new DataInputStream(socket.getInputStream());

                String ret = "";
                byte[] bytes = new byte[1024 * 1024];
                while (input.read(bytes) != 0) {
                    ret += KeyApplication.bytesToHexString(bytes) ;
                    if (input.available() == 0) { //一個請求
                        break;
                    }
                }
                //這裡要注意和客戶端輸出流的寫方法對應,否則會拋 EOFException
                // 處理客戶端資料
                System.out.println("客戶端返回內容:" + ret.trim());
                // 向客戶端回覆資訊
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                //System.out.print("請輸入:\t");
                // 傳送鍵盤輸入的一行
                //String s = new BufferedReader(new   InputStreamReader(System.in)).readLine();
                String s = "我已收到!";
                byte[] bytes1 = s.getBytes("utf-8");
                System.out.println("服務端傳送內容:" + s);
                out.write(bytes1);
                out.close();
                input.close();

注意!

檢視自己的編碼格式,檢視完成之後不要操作socket 中的任何東西,否則byte陣列會莫名其妙丟失一個

.....

具體原因未查....

trim的原因是把 byte轉String 中String中的空格(或者說是byte中0)的部分去掉。