JAVA socket 通讯中文乱码问题

近日准备研究android...所以在此之前复习一下j2se的好....

复习到socket时,,遇到个中文乱码问题,,,

我知道java是unicode的,C那神马的不是...通讯有点问题...

调试了几次,,,找到解决方法....UTF-16


为了防止忘记,还有日后能方便复习..于是,贴出代码 

package com.memorycat.test.net;

import java.net.*;
import java.io.*;

public class TestSocketC {

	TestSocketC() {
		try {
			Socket s = new Socket("127.0.0.1", 12345);
			BufferedReader toWrite = new BufferedReader(new InputStreamReader(
					System.in));
			InputStream in = s.getInputStream();
			OutputStream out = s.getOutputStream();

			String str = "草泥马";
			System.out.println("发出数据:" + str);
			out.write(str.getBytes("UTF-16"));
			out.flush();

			byte[] b = new byte[1024];
			in.read(b);
			System.out.println("接收数据:"+new String(b, "UTF-16"));

			out.close();
			s.close();

		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new TestSocketC();
	}

}

评论列表