Application of Game Theory to Implement Timeout in Java Socket Programming
James C. Whorley, Student, Radford University: ITEC 451
Abstract—Java sockets are the easiest way to implement a server/ client relationship with a TCP background.  With the use of the “Prisoner’s Dilemma” a subset of Game Theory, an extended class of Java’s Socket API can be used to implement a user/system based time out system.  The following statement is a transcription of the research and development of such class.

Index Terms—Java, Sockets, Programming, Game Theory  
I.	INTRODUCTION

T
his document is an informative paper on the design, development and implementation of timeouts in regards to server/client applications developed off Java’s pre-existing socket programming.  
A.	Justification
Without a stateful firewall or a similar controlling OS program, the timeout of a specific connection is left to the discretion of each client side application.  Although a stateless firewall can block certain ports and types of connections, it doesn’t lead to the effective control of open or “dead” connection states.  In the scope of Java’s socket programming, there has not been an object designed to quickly and efficiently implement a control to socket based programs.
B.	Background Knowledge
	Before continuing onward with this paper, a few ideas and concepts need to be understood.  Below is a list of summarized topics that need to be understood before this document can become useful to the reader.

-	A stateful firewall and some proxies maintain a list of connections.  Because of the finite amount of memory that each one has, to prevent memory overflows they discard the oldest connection before creating a new one.[1]
-	Socket programming has many excellent reviews for making basic connections to servers through both TCP and UDP protocols.[2]
-	Communication through networks is handled by a steady stream of bits broken into packets of varying size referred to as datagrams.  As a Java programmer, the concepts of packets are lost, however there instead is a level of abstraction to control such communication.  This level of abstraction is where the socket programming resides.  A socket’s purpose is to provide four basic functions: Connect to a remote machine, Send data, Receive data, and Close the connection. [3]

Java’s Socket API is a very simple way to implement a connection.  Understanding of the methods and structure is critical to the understanding of how this solution is implemented.  Reference for Java’s Socket API can be found online. [4]

Prisoner’s Dilemma is explained with the following scenario.  When two conspiring criminals are brought in for questioning, there are four possible scenarios that can result when they are questioned in separate rooms.  The only possible win solution is for both prisoner’s to stick to their story, regardless of what the questioning officer says.  Below the table shows the four scenarios using “1” as the win condition.  The win condition is that both prisoner’s go free.

“Prisoner’s Dilemma” Game Theory Logic	
	Prisoner 2	
	Doesn’t Talk	Talks	
Prisoner 1	Doesn’t Talk	1	0	
	Talks	0	0	

The main concept that the previous table states, is that if and only if both prisoners refuse to talk that they will be let go.  This logic is used in this project to implement a timeout solution to the current Java Socket API.  In this solution, as shown in the table below, the socket will only timeout and close the connection if and only if both the system and user timers expire.  The below scenario uses “1” to mark the time that the connection will close due to the timeouts of both the user and the system.  

TimeOutSocket Game Theory Implementation	
	System State**	
	Inactive	Active	
User State*	Inactive	1	0	
	Active	0	0	
* Inactive User State defined as no user activity for 10 minutes.
** Inactive System State defined as no system activity for 1 minute.

II.	Problem Statement

There are standards across the board for almost every aspect of the IT community which control the level of consistency for a given field.  The field of socket programming however does not consist of an easily implemented object which can control the logic of determining connection states.  Without this level of consistency and the ability to standardize the connections alive state, there is still a lot of unknown vulnerability to a system.  The solution is to create a working timeout model which eases the burden of developers when they are implementing a socket communication design.  This solution will utilize Game Theory, or more specifically the Prisoners’ Dilemma, to control the connection state of each Socket.  By implementing this solution, the developers can then be confident that they have a solid standard approach to create a working solution.

III.	Approach To Solve the Problem

The approach to this solution included the following stages: Design, Research, Modification, Development, and Testing. 

A.	Phases of Research and Development

1.	Design:  This step included the creation of CRC cards that would be used to extend the current Socket API.  The outcome of the design phase was to determine function requirements.
2.	Research: Once the overall design had been developed, it was compared back to the initial research to verify that all needed requirements had been identified and met.
3.	Modification: By using the new knowledge that was learned by revisiting the initial research, any needed modifications were made to the original design plans.
4.	Development: Following standard conventions of Object Oriented Design and JavaDocs the modified design was implemented into a form of useable code. **Note due to time restraints, some functionality was limited to pseudo code.
5.	Testing: This final phase was all dependent on the time restraint.  Testing was completed using the current running Ubuntu 12.04 server at place of research.  Only basic level testing was completed within the given time frame of three weeks.

B.	Timeline to Conduct Research

The hard deadline for this project was May 4th, 2014.  Given the restricted period of available time for adequate research, cutbacks on testing was implemented.  

Research Hard Deadlines	
April, 23rd, 2014	Design, Revisit Research, and Modification steps complete.	
April, 30th, 2014	Development complete.	
May 4th, 2014	Project submission due, results from testing depending on time restraint.	

C.	Tools Used
-	Eclipse Standard SDE build version 4.3.2
-	Ubuntu Server 12.04: Connection server
-	Windows 7/8: Client test machines using Eclipse’s runtime environment

IV.	Results

Below are the crucial segments of the finished program.  With each segment of code below will include an explanation of what purpose the segment holds.  Full versions of TimeOutSocket and supporting classes can be found in the Appendix.

A.	Steps of the Communication Structure

1.	Server program runs listening for a client to connect on the specified port.
2.	Client queries the server name and port it would like to connect to.
3.	If connection parameters are valid, the connection is established and communication can begin.
4.	Once connection has been established, time out parameters are established and passed to the created sockets.
5.	Once socket starts, the client creates an outgoing channel to send a message
6.	Upon receiving the client’s message, the server sends back a response message.
7.	The client receives a message and then sets system state to false, indicating that the write/read operation is done.
8.	Once timeout threads have reached 0 or user has specifically set both user and system states to false, the connection will close.

B.	Implementation of Timeout Structure

To successfully implement a timeout structure there were many additional methods and variables that needed to be added to the existing Socket framework to create a working solution.  The following table describes the added methods and variables used to design the solution shown.

Variables Added to Socket Framework	
Name	Type	Purpose	
userTimeOut	int	Holds the amount of time in seconds before user times out.	
systemTimeOut	int	Holds the amount of time in seconds before the system times out.	
userDone	boolean	Holds the True/False value of the user’s activity.	
systemDone	boolean	Holds the True/False value of the system’s activity.	
user	Countdown	Thread of type Countdown, a private subclass of TimeOutSocket which uses the userTimeOut value to count down the remaining seconds until the user times out.	
system	Countdown	Thread of type Countdown, a private subclass of TimeOutSocket which uses the systemTimeOut value to count down the remaining seconds until the system times out.	
timeout	Thread	Controls the overall thread of both the connection and both timers.	

Methods Added to Socket Framework	
Name	Return Type	Parameters
Taken	Purpose	
start	void	N/A	This begins the initial countdown of the socket.  This method should be called directly after the connection has been established.	
setUserTimeout	void	int – seconds	Takes an int parameter that sets the user’s timeout value.	
getUserTimeout	int	N/A	Returns the user’s remaining time in seconds	
setSystemTimeout	void	int – seconds	Takes an int parameter that sets the system’s timeout value in seconds.	
getSystemTimeout	int	N/A	Returns the user’s remaining time in seconds	
setUserDone	void	N/A	Sets the userDone boolean value to false.	
userIsDone	boolean	N/A	Returns the current value of the user’s status as a boolean.	
setSystemDone	void	N/A	Sets the systemDone boolean value to false.	
systemIsDone	boolean	N/A	Returns the current value of the system’s status as a boolean.	

V.	Concluding Remark

Overall the above methods and variables were easy to implement given Java’s already solid Socket API.  However, like any great solution there is always to be many bumps in the road.  Because of the time constraint and lack of resources there were a few bugs that were not worked out.  The main bug in the current solution is that the two threads controlling the user and system timers will not stop after the connection has been told to close.  One possible solution to this problem is to implement a check in the countdown’s loop to stop if the thread is interrupted and then interrupt it from the TimeOutSocket class.  Because of the time constraint this solution was entertained as a possibility but however a working model with this idea was not able to be implemented.
VI.	Appendix
A.	TimeOutSocket.java
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
 * @author MiniMe
 * @version 1.0
 * @category Child of Socket class in java.net */
class TimeOutSocket extends Socket {
	private int userTimeOut = 600;
	private int systemTimeOut = 6000;
	private boolean userDone = false;
	private boolean systemDone = false;
	private Countdown user = new Countdown();
	private Countdown system = new Countdown();
	private TimeOut timeoutThread = new TimeOut();
	//This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server.
	public TimeOutSocket(String host, int port) throws UnknownHostException, IOException{
		super(host, port);}
	//This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server.
	public TimeOutSocket(InetAddress host, int port) throws IOException{
		super(host, port);}
	//This method is identical to the previous constructor, except that the host is denoted by an InetAddress object.
	public TimeOutSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException{
		super(host, port, localAddress, localPort);}
	//Connects to the specified host and port, creating a socket on the local host at the specified address and port.
	public TimeOutSocket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException{
		super(host, port, localAddress, localPort);}
	//This method is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a String
	public TimeOutSocket(){
		super();}
	//This method begins socket timeout
	public void start(){
		user.setTime(getUserTimeOut());
		user.start();
		system.setTime(getSystemTimeOut());
		system.start();
		timeoutThread.start();}
	/**
	 * @param timeout
	 * Sets the user timeout period for further user customization  */
	public void setUserTimeOut(int timeout){
		userTimeOut = timeout;}
	/**
	 * @return userTimeOut
	 * Returns the value of the specified user timeout	*/
	private int getUserTimeOut(){
		return userTimeOut;}
	/**
	 * Sets user done status to true */
	public void setUserDone(){
		userDone = true;}
	/**
	 * @return done
	 * Returns true if the user is done */
	private boolean userIsDone(){
		return userDone;}
	
/**
	 * @param timeout
	 * Sets the system timeout period for further user customization */
	public void setSystemTimeOut(int timeout){
		systemTimeOut = timeout;}
	/**
	 * @return systemTimeOut
	 * Returns the specified system timeout period */
	private int getSystemTimeOut(){
		return systemTimeOut;}
	/**
	 * Sets the system done status to true */
	public void setSystemDone(){
		systemDone = true;}
	/**
	 * @return systemDone
	 * Returns true if the system is done */
	private boolean systemIsDone(){
		return systemDone;}
	/**
	 * @author MiniMe
	 * Private helper class to run the timeout checks in the background of current process */
	private class TimeOut extends Thread{
		public void start(){
			while(!userIsDone()&&!systemIsDone()){
				System.out.println("While loop increment");
				if (systemIsDone() && !userIsDone()){
					system = new Countdown();
					system.start();}
				else if (!systemIsDone() && userIsDone()){
					user = new Countdown();
					user.start();}
				else if (systemIsDone() && userIsDone()){
					System.out.println("Socket Closed");
					user.invalidate(false);
					system.invalidate(false);
					try {
						close();} 
					catch (IOException e) {
						// TODO Auto-generated catch block
						//e.printStackTrace();}}
				else if(!user.isAlive()){
					setUserDone();}
				else if(!system.isAlive()){
					setSystemDone();}
			}}}
}

B.	Countdown.java
public class Countdown extends Thread{
	private int timeToRun = 0;
	private boolean valid;
    @Override
    public void run() {
    	valid=true;
        this.runTimer(); }
    void setTime(int x){
    	timeToRun = x;  }
    void invalidate(boolean x) {
    	valid = x;}
    public int getTime() {
    	return timeToRun; }
    public void runTimer(){
         while (valid && timeToRun>0){
          try {
            timeToRun--;
            super.sleep(1000L);     }
           catch (InterruptedException e) {  //Stop if interrupted
        	   System.out.println("Thread interrupted.");   }    }
    }
VII.	Acknowledgment
The preferred spelling of the word “acknowledgment” in American English is without an “e” after the “g.” Use the singular heading even if you have many acknowledgments. Avoid expressions such as “One of us (S.B.A.) would like to thank ... .” Instead, write “S.B.A. thanks ... .” Sponsor and financial support acknowledgments are placed in the unnumbered footnote on the first page.
VIII.	References
[1]	http://itsitrc.blogspot.com/2013/12/client-server-socket-programming-in-java.html
[2]	Mattew Cook and Syed(shawon)M. Rahman,” Java and C/C++ language feature in terms of Network Programming,” 2005. 
[3]	Elliotte Rusty Harold,”Java Network Programming,” O’Reilly, 3rd edition, October 2004.
[4]	http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html

James C. Whorley Born in Roseville, CA and raised on the opposite of the Sierra Nevada mountains.  Joined the US Army in the summer of 2006 and served for 6 ½ years as an Imagery Intelligence Analyst.  While in training Mr. Whorley earned half the needed credits for his AAS in Military Intelligence.  Upon earning an Honorable Discharge in the fall of 2011 Mr. Whorley enrolled in Radford University’s Computer Science program. The author graduated with Honors from Radford University in May of 2014.  The author’s degrees earned were a B.S. in Computer Science with a Networking concentration and a B.S. in Geospatial Science with a GeoInformatics concentration. 
	While he attended Radford University he was recognized as the recipient of the 2014 Who’s Who amoung American Colleges and Universities.  He was also awarded Dean’s List for the entirety of his attendance at Radford University.  Additionally, upon graduation, he was named the 2014 Unsung Hero of Radford University’s Veterans.  While serving in the US Army he earned several Army Commendation Medals, Good Conduct Medals, and several service stripes for his duty overseas.