本帖最后由 Henry_YQH 于 2014-06-03 09:37:00 编辑

解决方案 »

  1.   

    你的message = new String(buffer, "GB2312").trim();写在构造方法里,只会读一遍。把你的线程方法稍微改了下:
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.PrintStream;
    import java.net.Socket;
    import java.util.logging.Level;
    import java.util.logging.Logger;public class EchoThread extends Thread {    protected PrintStream out;
        protected String message;
        protected Socket clientSocket;    public EchoThread(Socket clientSocket) {
            super();
            try {            this.clientSocket = clientSocket;
                // 获得输出输出流
                out = new PrintStream(clientSocket.getOutputStream());
            } catch (IOException ex) {
                System.out.println("EchoThread构造方法异常信息:");
                ex.printStackTrace();
                try {
                    clientSocket.close();
                } catch (Exception ex1) {
                    Logger.getLogger(EchoServerThread.class.getName()).log(Level.SEVERE, null, ex1);
                }
            }
        }    public void run() {
            try {
                // 接受数据,但不允许有中文,因为会乱码
                DataInputStream in = new DataInputStream(clientSocket.getInputStream());
                byte[] buffer = new byte[10000]; // 缓冲区的大小
                while (in.read(buffer) > 0) {
                    // 处理接收到的报文,转换成字符串
                    /**
                     * C++传递过来的中文字,需要转化一下。C++默认使用GBK。 GB2312是GBK的子集,只有简体中文。因为数据库用GB2312,所以这里直接转为GB2312
                     * */
                    message = new String(buffer, "GB2312").trim();
                    System.out.println("receive = " + message);
                }
                /**
                 * 这里需要使用底层的byte方法来传递。因为即使直接写字符串,到底层还是调用了传递byte的方法。 这里涉及到编码问题。C++默认使用GBK,而GB2312是GBK的子集。
                 */
                if (clientSocket.isConnected()) {
                    out.write("connect".getBytes());
                } else {
                    out.write("Socket id closed!".getBytes());
                }        } catch (Exception ex) {
                System.out.println("EchoThread run方法异常信息:");
                ex.printStackTrace();
            }
        }    public String getMessage() {
            return message;
        }    /**
         * 获取输出流
         * 
         * @return
         */
        public PrintStream getOutputStream() {
            return out;
        }
    }说实话,感觉看你在构造方法里做了不少逻辑操作,看着挺难受的。
    自己再调试下吧。