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?