In part 1 of this series, we saw a general overview of what sockets are, and how JSSE is used to secure that data transfer. Now we’re going to dive in and write our own encrypted server/client system.
Before we begin working with encryption, we should begin with the basics, so let’s start with a refresher on standard java sockets, which allow transfer of data between two computers over the internet. One of these computers is the “server” which constantly listens for incoming connections, and the other is the “client” which contacts the server and initiates the connection. We’ll start by creating a server to listen for incoming connections. We can choose whatever port we want, although it’s best to pick on that isn’t being used by anything else.
public void listen() {
int port = 54321;
try {
// create the listening socket
ServerSocket serverSocket = new ServerSocket( port );
while (true) {
// listen for a connection
Socket socket = serverSocket.accept();
System.out.println( "Incoming connection from " + socket.getInetAddress() );
// setup the input/output for the newly connected socket
BufferedReader socketIn = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
PrintWriter socketOut = new PrintWriter( socket.getOutputStream() );
// interact with the client
socketOut.println( "Thank you for connecting! What is your name? " );
socketOut.flush();
String name = socketIn.readLine();
socketOut.println( "Hello " + name + "!" );
socketOut.flush();
// close the socket
socketIn.close();
socketOut.close();
socket.close();
}
} catch ( IOException ex ) {
System.out.println( ex.toString() );
}
}
You can see in the code that we are creating a new ServerSocket object. The accept() method of this object will block until a client attempts to make a connection, then will return the socket connection that is created. We then create the input and output streams for sharing data with the client. Once we have finished our interaction, we close both streams and the socket itself. An IOException is thrown if the socket fails to be created for any reason.
Part 3 of this series will continue our venture into basic socket communication.