Groovy Tcp client/server sending maps

蓝咒 提交于 2020-01-03 05:19:09

问题


I created a basic tcp client and server in groovy and I'm wanting to send maps from the server to the client, I'm wondering if I'm able send maps across and still being able to access the values.

//TCP Server
def book1 = [Title of Book: "Groovy Recipes", Author: "Scott Davis", Number of Pages: "241"]

server = new ServerSocket(2000)

println("Waiting for connection")

while(true) {
    server.accept() { socket ->
        socket.withStreams { input, output ->   

            w = new BufferedWriter(new OutputStreamWriter(output))
            String message = "Connection was successful"

            r = new BufferedReader(new InputStreamReader(input))

            while(true) {

                if(message != null) {
                    w.writeLine(message)
                    w.flush()
                    message = null
                }

                String a = r.readLine()

                if(a=="book1") {
                    message = book1
                } else {
                    message = "$a command unknown."
                    sendMessage(message)
                    println message
                    message = null
                }
            }
        }
    }
}

def sendMessage(String msg) {
    try {
        w.writeLine(msg)
        w.flush();
    } catch(IOException ioException) {
        ioException.printStackTrace();
    }
}

Here is my Client (where I'm wanting to receive the map and get the values)

//TCP Client

def grabBookInfo {
    queryData()  
}

public void queryData() {
    def hosts = ["localhost"]

    for(int aHost = 0; aHost < hosts.size; aHost++) {
        bookClient(hosts[aHost]);
    }
}

public void bookClient() {
    def commands = ["book1"]
    def answers = [commands.size]

    def requestSocket = new Socket(host, 2000)

    r = new BufferedReader(new InputStreamReader(requestSocket.getInputStream()));
    w = new BufferedWriter(new OutputStreamWriter(requestSocket.getOutputStream()));

    String message = "Connection was successful"

    message = r.readLine()
    println("Server>" + message)

    for(int n = 0; n < commands.size; n++) {
        sendMessage(commands[n]);
        answers[n] = r.readLine()
    }

    //get map values here
    //answers[0] = Book
    //println Book.['Title of Book']
    //println Book.['Author']
    //println Book.['Number of Pages']

    w.flush()
    w.close()
}

public void sendMessage(msg) {
    w.write(msg+"\r\n");
    w.flush();
    System.out.println("client>" + msg);
    }   
}

Am I on the right track?


回答1:


Serialize the maps, example

http://www.java2s.com/Tutorial/Java/0140__Collections/SerializingHashMaps.htm




回答2:


In the server, use ObjectOutputStream. In the client use ObjectInputStream.

Server:

private static final HashMap<String, Integer> TEST_MAP;
static {
    TEST_MAP = new HashMap<String, Integer>();
    TEST_MAP.put("one", 1);
    TEST_MAP.put("two", 2);
}
...

ServerSocket ss = new ServerSocket(port);
Socket socket = ss.accept();
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); 
out.writeObject(TEST_MAP);
out.close();

Client:

Socket socket = new Socket(HOST, PORT);
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Object o = in.readObject();
assert o instanceof HashMap<?, ?>;
@SuppressWarnings("unchecked")
HashMap<String, Integer> m = (HashMap<String, Integer>)o;
assertTrue(m.get("one") == 1);
assertTrue(m.get("two") == 2);
in.close();
socket.close();


来源:https://stackoverflow.com/questions/3481579/groovy-tcp-client-server-sending-maps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!