小编Dav*_*ain的帖子

套接字 InputStream 和 UTF-8

我正在尝试与 Java 聊天。一切正常,除了特殊字符不起作用。我认为这是一个编码问题,因为我Outputstream在 UTF-8 中对字符串进行编码,如下所示:

  protected void send(String msg) {
    
        try {
          msg+="\r\n";            
          OutputStream outStream = socket.getOutputStream();              
          outStream.write(msg.getBytes("UTF-8"));
          System.out.println(msg.getBytes("UTF-8"));
          outStream.flush();
        }
        catch(IOException ex) {
          ex.printStackTrace();
        }
      }
Run Code Online (Sandbox Code Playgroud)

但在我的receive方法中,我没有找到一种方法来做到这一点:

public String receive() throws IOException {
   
    String line = "";
    InputStream inStream = socket.getInputStream();    
                
    int read = inStream.read();
    while (read!=10 && read > -1) {
      line+=String.valueOf((char)read);
      read = inStream.read();
    }
    if (read==-1) return null;
    line+=String.valueOf((char)read);       
    return line; 
    
  }
Run Code Online (Sandbox Code Playgroud)

那么有没有一种快速的方法来指定缓冲区读取的字节是用 UTF-8 编码的?

编辑:好的,我试过BufferedReader这样的:

 public String receive() throws …
Run Code Online (Sandbox Code Playgroud)

java sockets encoding utf-8

4
推荐指数
1
解决办法
3万
查看次数

标签 统计

encoding ×1

java ×1

sockets ×1

utf-8 ×1