tcp

TCP home server test client

With the previous post setup I’ve written a very basic example of how to test the server. At the moment, there are no back and forth communications, just a simple send of a 4 byte header.

Run the server program first, and then run the test. These can actually be run in the same order from Eclipse.

The good news is, this also works over the internet. The ‘Global’ in the code hold a string of my web server address and also the port that my router has open.

So, all working as expected.

package com.wlgfx.client;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class WLGfxClientTest {

    public static void main(String[] args) throws IOException {
		String header = "HEAD";
		byte[] bytes = header.getBytes();
		
		InetAddress address = InetAddress.getByName(Global.server_address);
		String ip = address.getHostAddress();
		
		System.out.println("Server at: " + ip);
		Socket socket = new Socket(address, Global.server_port);
		
		OutputStream os = socket.getOutputStream();
		os.write(bytes, 0, bytes.length);
		os.close();
		
		socket.close();
	}
}

The output from the server will be:

WLGfx Home Server - Starting up
Shutdown hook attached
TCP Server thread started...
TCP Incoming socket handler
Got header: HEAD

Java server test 1 [UPDATED]

My first test for Java as a console daemon. There’s not much here at the moment and the project is in Eclipse IDE.

From Eclipse, right click on the project and select export and then export as a runnable jar. Then in the terminal just type:

java -jar myexportedjar.jar

The JVM will continue to run as long as there are non daemon threads still running as in the below code. Also note that the hook handler allows catching of CTRL+C and other errors.

UPDATE:

I’ve now added the actually tcp server code which has a timeout on the server socket to allow for the thread to shut down safely. And a thread to handle each incoming connection.

/*
 * WLGfxServer.java
 */


package com.wlgfx.server.home;

public class WLGfxServer {
    
	static TCPServer tcpServer = null;

	public static void main(String[] args) {
		System.out.println("WLGfx Home Server - Starting up");
		
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				System.out.println("Shutdown hook in progress");
				tcpServer.stop();
			}
		});
		System.out.println("Shutdown hook attached");
		
		tcpServer =  new TCPServer();
	}
}



/*
 * TCPServerTest.java
 */


package com.wlgfx.server.home;

import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer implements Runnable {
    
	private Thread thread = null;
	boolean stopServer;

	public TCPServer() {
		start();
	}
	
	public void start() {
		if (thread == null) {
			stopServer = false;
			thread = new Thread(this);
			thread.start();
		}
	}
	
	public void stop() {
		stopServer = true;
		while (thread != null) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void run() {
		System.out.println("TCP Server thread started...");
		
		ServerSocket serverSocket = null;
		
		try {
			serverSocket = new ServerSocket(Global.tcp_port);
			serverSocket.setSoTimeout(1000);
			
			while (stopServer == false) {
				try {
					Socket socket = serverSocket.accept();
					if (socket != null) new TCPSocketHandler(socket);
				} catch (InterruptedIOException e) {
					//System.out.println("Timed out socket");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		thread = null;
		
		System.out.println("TCP Thread finished...");
	}
	
	private class TCPSocketHandler implements Runnable {
		
		Thread thread = null;
		Socket socket = null;
		byte[] header = new byte[4];
		
		public TCPSocketHandler(Socket insocket) {
			socket = insocket;
			thread = new Thread(this);
			thread.start();
		}

		@Override
		public void run() {
			System.out.println("TCP Incoming socket handler");
			
			try {
				readSocketBytes(socket, header, 4);
				String head = new String(header, StandardCharsets.UTF_8);
				System.out.println("Got header: " + head);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		private void readSocketBytes(Socket socket, byte[] bytes, int len) throws IOException {
			int position = 0;
			
			InputStream in = socket.getInputStream();
			while (position < len) {
				int count = in.read(bytes, position, len - position);
				if (count >= 0) position += count;
				else throw new IOException();
			}
		}
	}
}

(I’m currently not well at the moment but I’m plodding on with some studies.)