Writing custom applications on Compute Engine requires the use of sockets to communicate with clients. Here’s a code example demonstrating how to read and write to sockets in Java.
Assume that client_socket is the socket communicating with the client:
/**
* Contains the socket we're communicating with.
*/
Socket client_socket;
Create a socket by using a ServerSocket (represented by server_socket ) to listen to and accept incoming connections:
Socket client_socket = server_socket.accept();
Then extract a PrintWriter and a BufferedReader from the socket. The PrintWriter out object sends data to the client, while the BufferedReader in object lets the application read in data sent by the client:
/**
* Handles sending communications to the client.
*/
PrintWriter out;
/**
* Handles receiving communications from the client.
*/
BufferedReader in;
try {
//We can send information to the client by writing to out.
out = new PrintWriter(client_socket.getOutputStream(), true);
//We receive information from the client by reading in.
in = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
/**
* Start talking to the other server.
*/
//Read in data sent to us.
String in_line = in.readLine();
//Send back information to the client.
out.println(send_info);
}//end try
catch (IOException e) {
//A general problem was encountered while handling client communications.
}
A line of text sent by the client can be read in by calling in.readLine() demonstrated by the in_line string. To send a line of text to the client, call out.println(send_info) where send_info represents a string. If an error occurs during communication, an IOException will be thrown and caught by the above catchstatement.
Remember to add the following imports:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.BufferedReader;