Groovy Tcp client/server sending maps
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 recei开发者_C百科ve 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?
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();
Serialize the maps, example
http://www.java2s.com/Tutorial/Java/0140__Collections/SerializingHashMaps.htm
精彩评论