服务器:

public static void main(String[] args) {
        int serverPort = 7896;
        ServerSocket listenSocket;
        Socket clientSocket;
        while (true) {
            try {
                listenSocket = new ServerSocket(serverPort);
                clientSocket = listenSocket.accept();
                DataInputStream in = new DataInputStream(clientSocket.getInputStream());
                byte[] buf = new byte[2048];
                int tag = in.read(buf);
                String jieshou = "";
                if (tag != -1) {
                    System.out.println("接收到的信息");
                    jieshou = new String(buf, 0, tag);
                }
                //业务处理

                System.out.println("服务器发送信息");
                DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
                String xmlReq = "";// 业务处理

                int size = xmlReq.getBytes().length;

                System.out.println(xmlReq);
                byte[] bt = new byte[size];
                szfsSync = null;
                bt = xmlReq.getBytes("GBK");
                out.write(bt);

                in.close();
            } catch (Exception e) {

            }
        }
    }
View Code

 

客户端:

 public static void main(String[] args) {
     String xmlReq = "发送的内容";
     String ip ="";
     int port = 7896;
        Socket soc = null;
        try {
            soc = new Socket(ip, port);
            DataOutputStream out = new DataOutputStream(soc.getOutputStream());
            byte[] bt = xmlReq.getBytes("GBK");
            out.write(bt);
            log.info("Data transmission  ··············");

            // 接收服务器的数据
            DataInputStream in = new DataInputStream(soc.getInputStream());
            byte[] buf = new byte[2048];
            int len = -1;
            StringBuffer data = new StringBuffer();
            while( (len=in.read(buf)) != -1  ){
                data.append( new String(buf,0, len,"GBK"));
            }
            
            in.close();
            out.close();
            soc.close();

            return data.toString();
        } catch (Exception e) {
            log.error(" socket connection failure: " + e);
        }
        return null;
    }
View Code

 

注意点:

1、发送数据有编码要求时,统一在发送的时候处理,比如服务器使用的是 gbk编码,而客户端使用utf-8 编码,转义两次会出问题。

gbk 转 utf-8

String  str = "世界和平";
// 编码转换
String  re1 = new String(str.getBytes("utf-8"),"gbk");
// 再转回来
String  re2 = new String(str.getBytes("gbk"),"utf-8");

2、接收数据的时候,注意字节大小。

3、关闭流。