使用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)的部分去掉。

猜你喜欢

转载自blog.csdn.net/weixin_42655593/article/details/85048297
今日推荐