我是靠谱客的博主 不安花瓣,这篇文章主要介绍java socket通讯中文乱码问题,现在分享给大家,希望可以做个参考。

话不多说上代码

 public void run() {
        //客户端一连接就可以写数据给服务器了
        new sendMessThread().start();
        super.run();
        try {
            // 读Sock里面的数据
            InputStream s = socket.getInputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = s.read(buf)) != -1) {
                System.out.println(getdate() + "  服务器说:  "+new String(buf, 0, len,"UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

可以很明显的看到,我在进行读服务器发送的信息时,我的编码集为UTF-8,直接将UTF-8改为GBK

 public void run() {
        //客户端一连接就可以写数据给服务器了
        new sendMessThread().start();
        super.run();
        try {
            // 读Sock里面的数据
            InputStream s = socket.getInputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = s.read(buf)) != -1) {
                System.out.println(getdate() + "  服务器说:  "+new String(buf, 0, len,"GBK"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

接下来是写的操作同等原理

            super.run();
            //写操作

            Scanner scanner=null;
            OutputStream os= null;
            try {
                scanner=new Scanner(System.in);
                os= socket.getOutputStream();
                String in="";
                do {
                    in=scanner.next();
                    os.write((""+in).getBytes("GBK"));
                    os.flush();
                } while (!in.equals("bye"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            scanner.close();
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

至于为什么这么写是因为网上发现有帖子说:“在服务端默认的编码情况下,JAVA的SOCKET接收需要GBK编码,而C#的接收需要UTF-8编码

最后

以上就是不安花瓣最近收集整理的关于java socket通讯中文乱码问题的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(37)

评论列表共有 0 条评论

立即
投稿
返回
顶部