Java Socket Programming

There is so much talk about APIs, Restful this and that .  This is fine, but sometimes you just want to run get a client and server to use plain old sockets.  I wrote a simple Java Client / Server earlier today (there is nothing amazing about it, but it does show how you can serialize an object over a socket).

Apologies for the lack of indent.  There is something wrong with the Wordpress plugin :0/

The code samples are in GitHub :O)

The Server:

package com.chocksaway;

import java.io.*; import java.net.ServerSocket; import java.net.Socket;

public class FileServer { public static void main(String[] args) throws IOException, ClassNotFoundException { if (args.length != 1) { System.err.println(“Usage: java FileServer “); System.exit(1); }

int portNumber = Integer.parseInt(args[0]);

try ( ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0])); Socket socket = serverSocket.accept(); ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream()); ) {

Student student = (Student) inputStream.readObject(); student.getPicture();

File dstFile = new File(“milesOut.jpg”); FileOutputStream fileOutputStream = new FileOutputStream(dstFile); fileOutputStream.write(student.getPicture()); fileOutputStream.flush(); fileOutputStream.close();

System.out.println(“Object received = “ + student); socket.close(); } catch (IOException e) { System.out.println(“Exception caught when trying to listen on port “

  • portNumber + “ or listening for a connection”); System.out.println(e.getMessage()); } } }

And the Client:

package com.chocksaway;

import java.io.*; import java.net.Socket; import java.net.UnknownHostException;

public class FileClient { private static byte[] getFileData(String name) throws IOException { File myFile = new File(name);

DataInputStream diStream = new DataInputStream(new FileInputStream(myFile)); long len = (int) myFile.length(); byte[] fileBytes = new byte[(int) len]; int read = 0; int numRead = 0; while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read, fileBytes.length - read)) >= 0) { read = read + numRead; }

return fileBytes; }

public static void main(String[] args) throws IOException {

if (args.length != 2) { System.err.println( “Usage: java FileClient "); System.exit(1); }

String hostName = args[0]; int portNumber = Integer.parseInt(args[1]);

try { Socket socket = new Socket(hostName, portNumber); ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream()); Student student = new Student(43, “Miles”, FileClient.getFileData(“/tmp/miles.jpg”) ); outputStream.writeObject(student); } catch (UnknownHostException e) { System.err.println(“Don’t know about host “ + hostName); System.exit(1); } catch (IOException e) { System.err.println(“Couldn’t get I/O for the connection to “ + hostName); System.exit(1); } } }

And the Student class:

package com.chocksaway;

import java.io.Serializable;

public class Student implements Serializable {

private static final long serialVersionUID = 5950169519310163575L; private int id; private String name; private byte[] picture;

public Student(int id, String name, byte[] picture) { this.id = id; this.name = name; this.picture = picture; }

public int getId() { return id; }

public void setId(int id) { this.id = id; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public byte[] getPicture() { return picture; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false;

Student student = (Student) o;

if (id != student.id) return false; if (name != null ? !name.equals(student.name) : student.name != null) return false;

return true; } public int hashCode() { return id; }

public String toString() { return “Id = “ + getId() + “ ; Name = “ + getName(); } }

Creating a JAR:

I have created two JAR files, from scratch, using two manifest file.

**These are **(SocketServer.mf):

Manifest-Version: 1.0

Class-Path: out/production/Socket/

Main-Class: com.chocksaway.FileClient

And (SocketServer.mf):

Manifest-Version: 1.0

Class-Path: out/production/Socket/

Main-Class: com.chocksaway.FileServer

**I created **the manifest files by using jar command-line jar tool:

jar cfm SocketClient.jar SocketClient.mf out/production/Socket/com/chocksaway/*.class

jar cfm SocketServer.jar SocketServer.mf out/production/Socket/com/chocksaway/*.class

Running java -jar SocketServer.jar 5001 will start the server running on port 5001 (on localhost).

Running java -jar SocketClient.jar 127.0.0.1 5001 will start the client, connecting to the server (on port 5001).

The client copies the /tmp/miles.jpg file (replace with your own), streams it to the server, which then saves it as milesOut.jpg

Author | Miles Davenport

Career programmer, who designs, assembles, fixes, and supports customers, software and systems.