用java写了一个简单得udp连接的二人聊天程序,但是为什么发送中文消息的时候对方就显示乱码??请高手指点

解决方案 »

  1.   

    看看 编码
    应该I/O编码有问题吧 需要把 gbk转化为对应的1字节编码然后传输吧。
      

  2.   

    把你的要发送的内容用utf-u编码
      

  3.   

    我接受数据报的函数是:
    try{
    byte[] array=new byte[100];
    receivepacket=new DatagramPacket(array,array.length);
    receivesocket.receive(receivepacket);
    textArea1.append("\nfrom"+receivepacket.getAddress()+": :");
    byte data[]=receivepacket.getData();
    String received=new String(data,0);
    textArea1.append(received);哪里是编码??不懂??请指教.......
      

  4.   

    把接收的String转换一下,str = new String(str,iso,gb2312);我记不太清了,你去查一下API
      

  5.   

    是有这个函数,public String(char[] value,
                  int offset,
                  int count)Allocates a new String that contains characters from a subarray of the character array argument. The offset argument is the index of the first character of the subarray and the count argument specifies the length of the subarray. The contents of the subarray are copied; subsequent modification of the character array does not affect the newly created string. Parameters:
    value - array that is the source of characters.
    offset - the initial offset.
    count - the length. 
    可是那三个参数怎么填,,,这没得查阿....忘指点!.............
      

  6.   

    String
    public String(byte[] bytes,
                  String charsetName)
    Constructs a new String by decoding the specified array of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array. 
    The behavior of this constructor when the given bytes are not valid in the given charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required. 应该是这个函数,new String(data,"GB2312").
    你还可以看下面这篇文章,写的非常清楚。
    http://www-128.ibm.com/developerworks/cn/java/java_chinese/index.html
      

  7.   

    谢谢大家..但是....
    我改成了:  byte data[]=receivepacket.getData();
    String received=new String(data,"gb2312");
    textArea1.append(received);但是还是乱码....怎么办....
      

  8.   

    你的发送代码是怎么弄的?
    如果你发送代码以其他编码格式发送,自然是乱码。
    下面是从我的程序抄过来的一个编码转换,将字符串从GBK方式转换到 ISO-8859-1方式,你可以自己更换参数试一试。
    new String(s1.getBytes("GBK"),"ISO-8859-1")不过你是用UDP何必这么麻烦。你可以用下对象串行化,将聊天的内容封装到一个对象中。
    这样就可以很方便的进行扩展了,也不用编码转换这么麻烦。
      

  9.   

    try{textArea1.append("\nto"+textField2.getText()+";"+textField1.getText());
    String s=textField1.getText();
    byte data[]=new byte[100];
    s.getBytes(0,s.length(),data,0);
    String ss=new String(s.getBytes("GBK"),"ISO-8859-1");
    sendpacket=new DatagramPacket(data,ss.length(),InetAddress.getByName(textField2.getText()),5001);
    sendsocket.send(sendpacket);还是不行...大家有没有这方面的网页或者书籍可以告诉我名字,我去好好看下....哎!