繁体   English   中英

如何通过 TCP 发送 JSONobject?

[英]How to send JSONobject over TCP?

我试图了解如何发送我的自定义对象“纸”,它通过 TCP 使用 JSON 序列化。

客户端:

import org.json.JSONObject;

import java.io.*;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import model.*;
import view.*;

/**

 */
public class JSONClient {

    private String host;
    private int port;
    private Socket socket;
    private final String DEFAULT_HOST = "localhost";


    public void connect(String host, int port) throws IOException {
        this.host = host;
        this.port = port;
        socket = new Socket(host, port);
        System.out.println("Client has been connected..");
    }


    /**
     * use the JSON Protocol to receive a json object as
     *  from the client and reconstructs that object
     *
     * @return JSONObejct with the same state (data) as
     * the JSONObject the client sent as a String msg.
     * @throws IOException
     */
    public JSONObject receiveJSON() throws IOException {
        InputStream in = socket.getInputStream();
        ObjectInputStream i = new ObjectInputStream(in);
        JSONObject line = null;
        try {
            line = (JSONObject) i.readObject();
            
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
             e.printStackTrace();
        
        }
        
        
        return line;

    }


    public void sendJSON(JSONObject jsonObject) throws IOException {
           JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("key", new Paper(250,333));
        
         
         OutputStream out = socket.getOutputStream();
        ObjectOutputStream o = new ObjectOutputStream(out);
         o.writeObject(jsonObject2);
        out.flush();
        System.out.println("Sent to server: " + " " + jsonObject2.get("key").toString());
    }


    public static void main(String[] args) {
        JSONClient client = new JSONClient();
        try{

            client.connect("localhost", 7777);
            // For JSON call sendJSON(JSON json) & receiveJSON();
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("key", new Paper(250,333));

            client.sendJSON(jsonObject2);
            client.receiveJSON();
        }

        catch (ConnectException e) {
            System.err.println(client.host + " connect refused");
            return;
        }

        catch(UnknownHostException e){
            System.err.println(client.host + " Unknown host");
            client.host = client.DEFAULT_HOST;
            return;
        }

        catch (NoRouteToHostException e) {
            System.err.println(client.host + " Unreachable");
            return;

        }

        catch (IllegalArgumentException e){
            System.err.println(client.host + " wrong port");
            return;
        }

        catch(IOException e){
            System.err.println(client.host + ' ' + e.getMessage());
            System.err.println(e);
        }
        finally {
            try {
                client.socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

服务器 :

import model.*;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 */
public class JSONServer {


    private ServerSocket serverSocket;
    private int port;
    public static int clients = 0;


    public void establish(int port) throws IOException {
        this.port = port;
        serverSocket = new ServerSocket(port);
        System.out.println("JSONServer has been established on port " + port);

    }


    public void accept() throws IOException {
        while (true) {
            Socket socket = serverSocket.accept();
            Runnable r = new MyThreadHandler(socket);
            Thread t = new Thread(r);
            t.start();
        }
    }

    private static class MyThreadHandler implements Runnable {
        private Socket socket;

        MyThreadHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            clients++;
            System.out.println(clients + " JSONClient(s) connected on port: " + socket.getPort());

            try {
                // For JSON Protocol
                JSONObject jsonObject = receiveJSON();
                sendJSON(jsonObject);

            } catch (IOException e) {

            } finally {
                try {
                    closeSocket();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public void closeSocket() throws IOException {
            socket.close();
        }


        /**
         * use the JSON Protocol to receive a json object as
         * String from the client and reconstructs that object
         * @return JSONObejct with the same state (data) as
         * the JSONObject the client sent as a String msg.
         * @throws IOException
         */
        public JSONObject receiveJSON() throws IOException {
            InputStream in = socket.getInputStream();
            ObjectInputStream i = new ObjectInputStream(in);
            JSONObject line = null;
            try {
                line = (JSONObject) i.readObject();
                
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                 e.printStackTrace();
            
            }
            
            JSONObject jsonObject = new JSONObject(line);
            System.out.println("Got from client on port " + socket.getPort() + " " + jsonObject.get("key").toString());
            return jsonObject;
        }


        public void sendJSON(JSONObject jsonObject) throws IOException {
               JSONObject jsonObject2 = new JSONObject();
             jsonObject2.put("key", new Paper(250,369));
             
             OutputStream out = socket.getOutputStream();
              ObjectOutputStream o = new ObjectOutputStream(out);
             o.writeObject(jsonObject2);
              out.flush();
              System.out.println("Sent to server: " + " " + jsonObject2.get("key").toString());
    }
    }

    public void start(int port) throws IOException{
        establish(port);
        accept();
    }

    public static void main(String[] args) {
        JSONServer server = new JSONServer();

        try {
            server.start(7777);

        } catch (IOException e) {
            System.err.println(e.getMessage());
            System.err.println(e);
        }
    }
}

虽然类论文是序列化我得到错误:

本地主机 org.json.JSONObject

java.io.NotSerializableException: org.json.JSONObject

您正在使用ObjectOutputStream来序列化您的数据。 该序列化使用它自己的实现,将Serializable对象转换为字节表示,然后通过您的套接字发送。

JSON 用于将对象序列化为String表示形式。 不幸的是,您从不使用 json 序列化,而是尝试通过您的套接字发送您的 JSON 对象。

我的建议:使用将您的对象转换为字符串

String strJson = jsonObject.toString();

然后使用您的ObjectOutputStream发送一个字符串。 在接收端将其读取为字符串,然后通过将该字符串传递给构造函数将其转换回 JSONObject:

JSONObject js = new JSONObject(strJson);

只需将行更改为

        o.writeObject(jsonObject2.toString());

使用 .toString() 方法获取 JSONObject 的字符串。

这个对我有用 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM