socket做客户端服务端通信,返回json

服务端代码:

package ywt.socketserver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

import net.sf.json.JSONObject;



public class Server {

    public static void main(String[] args) {

        try {
              ServerSocket serverSocket = new ServerSocket(8885);
              System.out.println("启动服务器....");
              Socket socket = serverSocket.accept();


                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                //读取客户端发送来的消息
                String mess = br.readLine();
                System.out.println("我收到了客户端的东西"+mess);
                JSONObject object = JSONObject.fromObject(mess);
                //已接收到客戶端发来的内容,下面进行处理
                String dateTime=(String)((JSONObject)object.get("reqData")).get("dateTime");    
                System.out.println("dateTime="+dateTime);

                String jsonRsp="{\"version\":\"1.0\",\"charset\":\"UTF-8\",\"rspData\":{\"rspCode\":\"MSS3107\",\"rspMsg\":\"PAY3107,无效的键值\"}}";

                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

                bw.write(jsonRsp+"\n");
                bw.flush();


            bw.close();
            br.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

客户端:

package ywt.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

import net.sf.json.JSONObject;

public class PostParams {
    //使用socket来传输json
    public String postParams(String jsonParams,String url){

            try {
                // Socket s = new Socket("127.0.0.1",8885);
                Socket s=new Socket(url,8885);

                 //构建IO
                 InputStream is = s.getInputStream();
                 OutputStream os = s.getOutputStream();

                 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

                 //向服务器端发送一条消息
                 bw.write(jsonParams+"\n");
                 bw.flush();

                 //读取服务器返回的消息
                 BufferedReader br = new BufferedReader(new InputStreamReader(is));
                 String mess = br.readLine();
                 System.out.println("服务器发来的消息:"+mess);
                 return mess;
            } catch (Exception e) {
                return "error";
            }

    }
}

你可能感兴趣的:(socket)