Speaking of java...

Discussion in 'OT Technology' started by Fantik, Jun 13, 2003.

  1. Fantik

    Fantik Guest

    I just finished this rough iteration of a client-to-client instant messanger program that gently probes a specified section of the network looking for other users, so a server is not needed, yet you don't need to know other people's IPs to communicate with them.

    Some of you might find it informative or interesting, so I figured id post it. enjoy.

    any questions about it? post

    Code:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    
    public class InstantMessenger
    	{
    	/**************************************************************************
    						InstantMessenger.java
    
    	Written by:
    
    	Austin J. Murphy
    	[email][email protected][/email]
    
    	This program runs an Instant Messenger program.
    	1st. the user is asked to enter their desired username, this happens every
    	time the program is run.
    	next the user will be given a prompt.
    	hit enter to obtain control of the program, then either enter a command,
    	(quit, add (space) name (space) IP, or list)
    	or you can send a message to somebody that is on your list.
    	(command 'list' to see your contactlist) by typing
    	name (space) message to them.
    
    	this program will gently probe a specified section of the network for other users
    	that are currently running the same iteration of InstantMessenger.
    	to edit the subnets that are probed, change the contents of the String[] ipList.
    
    
    	This is the main driver class that creates the Command and Control objectd
    	and then starts it's run thread.
    
    	Modifications:
    		now you can enter the ip subnets (edit the contents of String[] ipList)
    		that will be probed for other users currently online.
    
    
    	**************************************************************************/
    
    	public static void main(String[] args) throws IOException
    		{
    		int sendMessagePort = 1717;
    		int receiveMessagePort = 1718;
    		String[] ipList = {"140.209.106.","140.209.107.","192.168.0.","140.209.64.","140.209.110.","140.209.112."};
    
    		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    
    
    
    		new Thread(new Controller(sendMessagePort, receiveMessagePort, ipList)).start();
    		}// public static void main
    	}// public class Driver
    
    
    	class Controller implements Runnable
    		{
    		/**************************************************************************
    								InstantMessageController.java
    
    		This class is the command and control class for all the threads in my program
    		it creates all of the threaded objects in the constructor, and then starts them
    		when this thread is run.
    
    		Methods:
    			InstantMessageController(int sendMessagePort, int receiveMessagePort)
    				constructor class that creates both incoming and outgoing queues as well
    				as the semaphore and the incoming message handler.
    			public void run()
    				starts all the threads and then waits for user input.  when input is received
    				it puts the message in the outgoing queue
    
    		Modifications:
    			getContactList  5/19
    			getSemaphore  5/19
    			getOutgoingQueue  5/19
    			getSendMessagePort   5/19
    			now receives list of ips to poll.   5/19
    			contains a string that stores your local name for sending areyoutheremessages to
    				people on the ipList	5/20
    		**************************************************************************/
    
    		Semaphore       accessControl;
    		Contacts		contactList;
    		Thread          handleMessage;
    		BufferedReader  input;
    		String[] 		ipList;
    		MessageQueue    messagesReceived;
    		MessageQueue    messagesToSend;
    		String 			name 					= "";
    		Thread			pollingTheNetwork;
    		Thread          queueReceiveMessage;
    		Thread          queueSendMessage;
    		int             receiveMessagePort;
    		Message         sendMessage;
    		int             sendMessagePort;
    		String          stringFromUser;
    
    		Controller(int sendMessagePort, int receiveMessagePort, String[] ipList) throws UnknownHostException, SocketException
    			{
    			this.sendMessagePort    = sendMessagePort;
    			this.receiveMessagePort = receiveMessagePort;
    			this.ipList 			= ipList;
    
    
    
    			contactList = new Contacts();
    
    			messagesToSend   = new MessageQueue(100);
    			queueSendMessage = new Thread(new QueueSendMessage(messagesToSend, sendMessagePort));
    
    			messagesReceived = new MessageQueue(100);
    			queueReceiveMessage = new Thread(new QueueReceiveMessage(messagesReceived, receiveMessagePort));
    
    			accessControl = new Semaphore();
    			handleMessage = new Thread(new HandleMessage(messagesReceived, this));
    			input = new BufferedReader(new InputStreamReader(System.in));
    
    			pollingTheNetwork = new Thread(new Poll(this));
    			}
    
    		public Contacts 	getContacts() 								{ return contactList; }
    		public Semaphore 	getSemaphore() 								{ return accessControl; }
    		public MessageQueue getOutgoingQueue() 							{ return messagesToSend; }
    		public int 			getSendMessagePort() 						{ return sendMessagePort; }
    		public String[] 	getIPList() 								{ return ipList; }
    		public String 		getUserName() 								{ return name; }
    		public InetAddress 	getLocalHost() throws UnknownHostException 	{ return InetAddress.getLocalHost(); }
    		public int 			getReceivingPort() 							{ return receiveMessagePort; }
    		public void 		setName(String name) 						{ this.name = name; }
    
    		public void run()
    			{
    			try
    			{
    			 while(name.length() < 1)
    			  {
    			   System.out.print("Who are you?: ");
    			   setName(input.readLine().trim());
    		      }
    	        getContacts().put(name,InetAddress.getLocalHost());
    	        }
    	        catch(Exception e) {}
    
    			StringTokenizer tokens;
    			String contact;
    			String message ="";
    			System.out.println("<Enter to begin>");
    
    			queueSendMessage.start();
    			queueReceiveMessage.start();
    			handleMessage.start();
    			pollingTheNetwork.start();
    
    			while(!Thread.currentThread().isInterrupted())
    				{
    				try
    					{
    					input.readLine();
    					while(!accessControl.keyboardReady()) {Thread.sleep(5);}
    
    					System.out.print("> ");
    					stringFromUser = input.readLine();
    					accessControl.doneWithKeyboard();
    
    
    					tokens = new StringTokenizer(stringFromUser, " ");
    
    					if(tokens.hasMoreTokens())
    					   contact = tokens.nextToken();
    					   else
    					   contact = "";
    
    					message = "";
    					if (contact.trim().length() > 0 && getContacts().contains(contact))
    						{
    						if(tokens.hasMoreTokens()) message = tokens.nextToken("");
    						if(message.trim().length() > 0)
    						  {
    						   sendMessage = new Message(name, message, getContacts().returnIP(contact), receiveMessagePort);
    						   sendMessage.enqueue(messagesToSend);
    					      }// if
    						}// if
    					else
    						{
    						if (contact.trim().equalsIgnoreCase("list"))
    							{
    							String[][] array;
    							array = getContacts().toArray();
    							for (int i=0; i<array.length; i++)
    								System.out.println(array[i][0] +"\t" + array[i][1]);
    							}// if
    						if (contact.trim().equalsIgnoreCase("add"))
    							{
    							getContacts().put(tokens.nextToken(), InetAddress.getByName(tokens.nextToken()));
    							}// if
    						if (contact.trim().equalsIgnoreCase("quit"))
    							{
    							pollingTheNetwork.interrupt();
    							queueReceiveMessage.interrupt();
    							handleMessage.interrupt();
    							queueSendMessage.interrupt();
    							Thread.currentThread().interrupt();
    							}// if
    						}// else
    					}// try
    				catch(InterruptedException e) { Thread.currentThread().interrupt(); }
    				catch(Exception e) {System.out.println("Controller.run(): " + e);}
    				}// while
    			}// run
    	}// class Controller implements Runnable
    
    	class Message implements Serializable
    	  {
    	   /*
    	     Patrick L. Jarvis
    	     April 15, 2003
    
    	     A class to model messages. This class must be extended with
    	     two subclasses: a send message subclass for messages that are
    	     to be sent from this user and a receive message subclass for
    	     messages that were sent to this user.
    
    	     Protocol
    	     Three message types are supported each type begins with the
    	     following information:
    	               PROTOCOL_NAME
    	               slash character
    	               PROTOCOL_VERSION
    	               tab character
    
    	     April 29, 2003
    	     New Methods:
    	         public void enqueue(MessageQueue) Message places itself into queue
    	         public void execute(Semaphore)    Message displays contents on monitor
    
    	     April 30, 2003
    	     Modifications
    	         Change the getPacket method to return a Datagram packet containing the
    	         serialized version of this Message object. Since objects are now being
    	         sent back and forth, there is no longer a need for the protocol.Change
    	         the method header to advertise IOException.
    
    	         Delete all protocol information.
    
    	         Rewrite setContent method to eliminate protocol stuff.
    
    	         Implement Serializable interface
    
    	         Delete DatagramPacket constructor
    	   */
    
    
    
    	   private String      contact; // name of person who sent message
    	   private String      content; // contents of message
    	   private InetAddress from;    // who sent message
    	   private InetAddress to;      // IP to whom message is being sent
    	   private int         toPort;  // port to whom message is being sent
    
    
    	   public Message(String contact, String content, InetAddress to, int toPort, InetAddress from)
    	   {
    		if(contact == null)
    		  throw new IllegalArgumentException("Message constructor: contact parameter is null");
    		if(content == null)
    		  throw new IllegalArgumentException("Message constructor: message parameter is null");
    		if(to == null)
    		  throw new IllegalArgumentException("Message constructor: to parameter is null");
    		if(from == null)
    		  throw new IllegalArgumentException("Message constructor: from parameter is null");
    
    		//this.message = message;
    		this.content = content;
    		this.contact = contact;
    		this.from    = from;
    		this.to      = to;
    		this.toPort  = toPort;
    	   }
    
    	   public Message (String contact, String content, InetAddress to, int toPort) throws IOException
    	   {
    		this(contact, content,to,toPort,InetAddress.getLocalHost());
    	   }
    
    	   public InetAddress getFrom()    { return from; }
    	   public String      getContact() { return contact; }
    	   public String      getContent() { return content; }
    	   public InetAddress getTo()      { return to; }
    	   public int         getToPort()  { return toPort; }
    	/*
    	                      Methods
    	*/
    
    	   public String toString()
    	     {
    		  //  Return the contents of the message as a String
    	      return "Packet from " + getContact() + " " + getFrom().getHostAddress() + " to "
    	             + getTo().getHostAddress() + "\n" + getContent();
    	     }
    
    
    	   public DatagramPacket  getPacket() throws IOException
    	     {
    		  //  Return a packet that contains the serialized version of
    		  //  this Message object.
    		  byte[]                bytes;
    	      ByteArrayOutputStream byteStream;
    	      ObjectOutputStream    objectStream;
    		  DatagramPacket        packet;
    	      //  Serialize this object to a byte array
    	      byteStream   = new ByteArrayOutputStream();
    	      objectStream = new ObjectOutputStream(byteStream);
    
    		  objectStream.writeObject(this);
    	      bytes = byteStream.toByteArray();
    	      objectStream.close();
    
    	      //  Put the serialized object into the Datagram packet
    		  packet = new DatagramPacket(bytes, bytes.length);
    		  packet.setAddress(getTo());
    		  packet.setPort(getToPort());
    		  return packet;
    		 }
    
    	   public void enqueue(MessageQueue queue) { queue.put(this); }
    
    	   public void execute(Controller controller)
    	    {
    	     Semaphore semaphore = controller.getSemaphore();
    
    	     //  Send an acknowledge back
    	     try
    	     {
    		  new AcknowledgeMessage(controller.getUserName(),
    	                             controller.getLocalHost(),
    	                             controller.getReceivingPort()).enqueue(controller.getOutgoingQueue());
    	      //  Update the contacts with this message sender
    	      controller.getContacts().put(getContact(),getFrom());
    	     }
    	     catch(IOException e)
    	     {
    		  System.out.println("IOException in Message.execute when sending acknowledge message");
    		 }
    	     //  Wait until the monitor is available.
    	     try { while (!semaphore.readyForDisplay()) Thread.sleep(100); }
    	     catch(InterruptedException e) {}
    	     System.out.println(getContact() + " says: " + getContent());
    		 semaphore.doneWithDisplay();
    	     } //   execute()
    }  // Message
    
    class AcknowledgeMessage extends Message
    {
    /*
       Patrick L. Jarvis
       May 5, 2003
    
       An extension to the Message class that models an Acknowledge message
    */
    
     AcknowledgeMessage(String contact, InetAddress to, int toPort) throws IOException
     {
      super(contact, "", to, toPort);
     }
    
     public String toString()
     {
       //  Return the contents of the message as a String
      return "Packet from " + getFrom().getHostAddress() + " to "
                 + getTo().getHostAddress() + "\nAcknowledge";
     }
    
    
     public void execute(Controller controller)
     {
      //  System.out.println("AcknowledgeMessage.execute()");
      //  Update the contacts with this message sender
      controller.getContacts().put(getContact(),getFrom());
     } //   execute()
    
    }  //  AcknowledgeMessage
    
    class AreYouThereMessage extends Message
    {
    /*
       Patrick L. Jarvis
       May 5, 2003
    
       An extension to the Message class. Used in the QM281
       InstantMessenger assigment.
    */
    
     AreYouThereMessage(String contact, InetAddress to, int toPort) throws IOException
     {
      super(contact, "", to, toPort);
     }
    
     public String toString()
     {
       //  Return the contents of the message as a String
      return "Packet from " + getFrom().getHostAddress() + " to "
                 + getTo().getHostAddress() + "\nAreYouThere";
     }
    
    
     public void execute(Controller controller)
     {
      // System.out.println("AreYouThereMessage.execute()");
      //  Send an AcknowledgeMessage
      try
      {
       new AcknowledgeMessage(controller.getUserName(),
    						  controller.getLocalHost(),
    						  controller.getReceivingPort()).enqueue(controller.getOutgoingQueue());
      }
      catch(IOException e)
      {
       System.out.println("IOException in AreYouThereMessage.execute when sending acknowledge message");
      }
      //  Update the contacts with this message sender
      controller.getContacts().put(getContact(),getFrom());
     } //   execute()
    
    }  //  AreYouThereMessage
    
    class Contacts
    	{
    	/**************************************************************************
    						Contacts.java
    	This class represents the list of potential contacts that you have connected with
    	somehow since you have started your instant messenger program.  A contact is a hashmap
    	entry that is a string for their name and an InetAddress for their IP.
    
    	Methods:
    		put(String name, InetAddress ip)
    			adds a new entry to the contactList
    		public InetAddress returnIp(String name)
    			when passed a name, returns their IP
    		public boolean contains(String contact)
    			is this name in your contact list yet?
    		public String[][] toArray()
    			returns an [][] array that contains the valueset and the keyset
    		private Iterator getIterator()
    			returns an iterator pointing at the keyset of the the contactlist
    
    	**************************************************************************/
    
    	private HashMap contactList;
    
    	public Contacts()
    		{
    		contactList = new HashMap();
    		}
    
    	public void put(String name, InetAddress ip)
    		{
    		contactList.put(name.toLowerCase().trim(), ip);
    		}
    
    	public InetAddress returnIP(String name)
    		{
    		if (contactList.containsKey(name.toLowerCase().trim()))
    			return (InetAddress) contactList.get(name.toLowerCase().trim());
    		else
    			return null;
    		}
    	public boolean contains (String contact)
    		{
    		return contactList.containsKey(contact.trim());
    		}
    
    	 public String[][] toArray()
    	 	{
    		// returns a two dimensional array that contains the valueset and the keyset.
    	    String[][] info;
    	    Iterator   iterator = getIterator();
    	    String	   output;
    
    	    info = new String[contactList.size()][2];
    
    	    for(int i=0; i<info.length; i++)
    	    	{
    
    			info[i][0] = (String) iterator.next();
    			info[i][1] = (returnIP(info[i][0])).getHostName();
    	    	}
    	    return info;
    		}// public String[][] toArray()
    
    	private Iterator getIterator() { return contactList.keySet().iterator(); }
    	}// public class Contacts
    
    	class Poll implements Runnable
    		{
    		/**************************************************************************
    							Poll.java
    		This class is just a thread that will continuously send AreYouThereMessages
    		to everybody on the specified sections of the network.
    
    		**************************************************************************/
    
    		Controller 	controller;
    		String[] 	ipList;
    
    
    		public Poll(Controller controller)
    			{
    			this.controller = controller;
    			this.ipList = controller.getIPList();
    			}
    
    		public void run()
    			{
    			// the sleep schedules in this thread are broken up a lot because most of this threads time is
    			// spent asleep.  so if this thread is interrupted, the longest that you'll have to
    			// wait is 5 seconds for it to terminate.
    			while (!Thread.currentThread().isInterrupted())
    				{
    				try
    					{
    					for (int i=0; i<ipList.length; i++)
    						{
    
    						for(int j=1; j<255; j++)
    							{
    							controller.getOutgoingQueue().put(new AreYouThereMessage(controller.getUserName(),
    							InetAddress.getByName(ipList[i] + j), controller.getSendMessagePort()));
    							Thread.sleep(250);
    							}// for
    						for(int minutes=0; minutes<1; minutes++)
    							for(int tenSeconds=0;tenSeconds<6; tenSeconds++)
    							{
    							Thread.sleep(5000);
    							Thread.sleep(5000);
    							}// for
    		 				}// for
    					for(int minutes=0; minutes<5; minutes++)
    						for(int tenSeconds=0;tenSeconds<6; tenSeconds++)
    						{
    						Thread.sleep(5000);
    						Thread.sleep(5000);
    					    }// for
    					}// try
    				catch (InterruptedException e) { Thread.currentThread().interrupt(); }
    				catch (Exception e) {System.out.println("Poll.run(): "+e);}
    			}// end while
    		}// end run()
    	}// public class Poll implements Runnable
    
    	class HandleMessage implements Runnable
    		{
    		/**************************************************************************
    							HandleMessage.java
    		This class handles messages that are coming in from the message queue that
    		it has a referance to.  when messages come into the queue, it displays them
    		on the screen.
    
    
    
    		Methods:
    			accessor methods for MessageQueue and Semaphore
    				public MessageQueue getIncomingQueue()
    				public Semaphore getSemaphore()
    			public void run()
    				when queue contains messages, will attemt to display them on screen
    
    		Modifications
    			instead of constructor getting a semaphore, I will get the entire
    				controller.  I can call the semaphore accossor methods now.
    			removed accessor for semaphore
    		**************************************************************************/
    
    		Controller 		controller;
    		MessageQueue 	messagesReceived;
    
    		HandleMessage(MessageQueue messagesReceived, Controller controller)
    			{
    			this.messagesReceived = messagesReceived;
    			this.controller = controller;
    			}
    
    		public MessageQueue getIncomingQueue()
    			{ return messagesReceived; }
    
    
    		public void run()
    			{
    		    Message message;
    
    			while(!Thread.currentThread().isInterrupted())
    				{
    				try
    					{
    					if(!getIncomingQueue().isEmpty())
    						{
    						message = getIncomingQueue().get();
    						message.execute(controller);
    						}
    					Thread.sleep(100);
    					}
    
    				catch(InterruptedException e) { Thread.currentThread().interrupt(); }
    				}
    			}
    	}// class HandleMessage implements Runnable
    
    	class MessageQueue extends Queue
    		{
    		/**************************************************************************
    							MessageQueue.java
    
    		This object is a special kind of queue FIFO that is specific to messages
    
    		Methods:
    			public synchronized void put(Message m)
    				checks if queue is full, if so it destroys a message and adds itself
    				if not, it adds itself
    			public synchronized Message get()
    			public synchronized Message peek()
    		**************************************************************************/
    
    		private int maxSize;
    
    		MessageQueue() 				{ this(10); }
    		MessageQueue(int maxSize) 	{ super(); this.maxSize = maxSize; }
    
    		public synchronized void put(Message m)
    			{
    			// if queue is full, destroys oldest message and adds itself.
    			// if not, adds itself
    			if(super.size() == maxSize) {get();}
    			super.put(m);
    			}
    		public synchronized Message get() { return (Message)super.getFromQueue(); }
    		public synchronized Message peek() { return (Message)super.peekAtFront();}
    	}// class MessageQueue extends Queue
    
    	class Queue
    		{
    		/**************************************************************************
    							Queue.java
    		This FIFO datastructure models a line in which objects can enter at the back
    		and wait to be called out the front.
    
    		Methods:
    			public synchronized int size()
    				returns length of queue
    			public Object getFromQueue()
    				grabs next object in line
    			public void put(Object o)
    				puts o at the end of the line
    			public Object peekAtFront()
    				returns next object in line without destroying it
    			public synchronized boolean isEmpty()
    				returns true if queue is empty
    		**************************************************************************/
    
    	    private Vector queue;
    
    	    public Queue() { queue = new Vector(); }
    	    public synchronized int size() { return queue.size(); }
    	    public Object getFromQueue() { return queue.remove(0); }
    	    public void put(Object o) { queue.add(o); }
    	    public Object peekAtFront() { return queue.elementAt(0); }
    	    public synchronized boolean isEmpty() { return (queue.size() < 1); }
    	}// class Queue
    
    	class QueueReceiveMessage extends ReceiveMessage implements Runnable
    		{
    		/**************************************************************************
    							QueueReceiveMessage.java
    
    		This object monitors the socket and when a message is received, places it in the queue
    
    		Methods:
    			QueueReceiveMessage(MessageQueue messagesReceived, int receiveMessagePort)
    				sets information to the socket and creates referance to incoming queue
    			public MessageQueue getIncomingQueue()
    				accessor for the queue
    			public void run()
    				when message is received, it is placed in the incoming queue
    		**************************************************************************/
    
    		Message 		message;
    		MessageQueue 	messagesReceived;
    
    		QueueReceiveMessage(MessageQueue messagesReceived, int receiveMessagePort) throws UnknownHostException, SocketException
    			{
    			super(InetAddress.getLocalHost(), receiveMessagePort);
    			this.messagesReceived = messagesReceived;
    			}
    		public MessageQueue getIncomingQueue()
    			{
    			return messagesReceived;
    			}// public MessageQueue getIncommingQueue()
    
    		public void run()
    			{
    			try
    				{
    				while(!Thread.currentThread().isInterrupted())
    					{
    					message = super.receive();
    					getIncomingQueue().put(message);
    					Thread.sleep(100);
    					}// while
    				}// try
    			catch(InterruptedException e) {Thread.currentThread().interrupt();}
    			catch(IOException e) {}
    	        }// public void run()
    	}// class QueueReceiveMessage extends ReceiveMessage implements Runnable
    
    	class QueueSendMessage extends SendMessage implements Runnable
    		{
    		/**************************************************************************
    							QueueSendMessage.java
    
    		This object monitors the queue and when a message is in the queue it sends
    		it to the socket
    
    		Methods:
    			QueueSendMessage(MessageQueue messagesToSend, int toPort)
    				constructor sets information about the socket and creates a referance
    				to the queue
    			public MessageQueue getOutgoingQueue()
    				accessor method for the outgoing queue
    			public void run()
    				monitors queue, if not empty, send the next message
    		**************************************************************************/
    
    		MessageQueue messagesToSend;
    
    		QueueSendMessage(MessageQueue messagesToSend, int toPort) throws UnknownHostException, SocketException
    			{
    			super(InetAddress.getLocalHost(), toPort);
    			this.messagesToSend = messagesToSend;
    			}
    
    		public MessageQueue getOutgoingQueue()
    			{
    			return messagesToSend;
    			}// public MessageQueue getOutgoingQueue()
    
    		public void run()
    			{
    			while(!Thread.currentThread().isInterrupted())
    				{
    				try
    					{
    
    					if(!getOutgoingQueue().isEmpty())
    						{
    						Message message = getOutgoingQueue().get();
    						super.send(message);
    						}// if
    					Thread.sleep(50);
    					}// try
    				catch (InterruptedException e) {Thread.currentThread().interrupt();}
    				catch (IOException e) { System.out.println("QueueSendMessage.run(): " + e);}
    				}// while
    			}// public void run()
    	}// class QueueSendMessage extends SendMessage implements Runnable
    
    	class ReceiveMessage extends SendReceiveMessage
    		{
    		/********************************************************************
    							ReceiveMessage.java
    		This object is used when receiving a message.  it has information
    		pertaining to receiving a datagrampacket from a socket
    
    		Methods
    			public Message getMessage()
    				calls the receive message on the socket and listens
    				until it receives a packet.
    				then creates a message from that packet and returns it.
    
    		********************************************************************/
    
    
    		private static final int MAX_BUFFER_SIZE = 2048;
    		private static byte[] buffer = new byte[MAX_BUFFER_SIZE];
    
    		ReceiveMessage(InetAddress to, int port) throws SocketException
    			{
    			// changes values of the socket to (to) and (port)
    			super(to, port);
    			}// ReceiveMessage(InetAddress to, int port) throws SocketException
    
    		public Message receive() throws IOException
    			{
    			// creates a packet with the max buffer size
    			// tells the socket to listen for a packet and receive it
    			// then returns the message that was extracted from the packet.
    			ByteArrayInputStream byteStream;
    			ObjectInputStream input;
    			byte[] data;
    			Message message = null;
    			try
    				{
    				DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
    				super.getSocket().receive(packet);
    				data = packet.getData();
    
    				byteStream = new ByteArrayInputStream(data);
    				input = new ObjectInputStream(byteStream);
    
    				message = (Message)input.readObject();
    
    				}
    			catch (ClassNotFoundException e) {}
    			return message;
    			}// public Message getMessage() throws IOException
    }// class ReceiveMessage extends SendReceiveMessage
    
    class Semaphore
    	{
    	/**************************************************************************
    						Semaphore.java
    
    	This object is a semaphore that locks the monitor and grants permission
    	when requested by either the keyboard or the incoming message that needs
    	to be displayed
    
    	Methods:
    		public synchronized boolean keyboardReady()
    			requests the monitor for typing on keyboard
    		public synchronized boolean readyForDisplay()
    			requests the monitor for the incoming message
    		public synchronized boid doneWithKeyboard()
    			releases the semaphore from the keyboard
    		public synchronized boolean doneWithDisplay()
    			releases the semaphore from the incoming message display
    	**************************************************************************/
    
    	boolean displayRequest;
    	boolean keyboardRequest;
    
    	Semaphore()
    		{
    		displayRequest = false;
    		keyboardRequest = false;
    		}
    	public synchronized boolean keyboardReady()
    		{
    		keyboardRequest = true;
    		return !displayRequest;
    		}
    	public synchronized boolean readyForDisplay()
    		{
    		displayRequest = !keyboardRequest;
    		return displayRequest;
    		}
    	public synchronized void doneWithKeyboard()
    		{
    		keyboardRequest = false;
    		}
    	public synchronized void doneWithDisplay()
    		{
    		displayRequest = false;
    		}
    	}// class Semaphore
    
    class SendMessage extends SendReceiveMessage
    	{
    	/****************************************************************
    						SendMessage.java
    	This object is what is used to send a Message.  It contains information
    	needed to set the Socket and also contains the actual send method
    
    	Methods:
    		public void send(Message message)
    			obtains the socket from SendReceiveMessage and then sends the
    			DatagramPacket associated with message via the socket.
    	****************************************************************/
    
    	private DatagramPacket packet;
    
    	SendMessage(InetAddress to, int toPort, InetAddress from) throws SocketException
    		{
    		// sends the IP and port number to SendReceiveMessage constructor.
    		// These are used to set up the DatagramSocket
    
    		super(to, toPort);
    		}// SendMessage(InetAddress to, int toPort, InetAddress from) throws SocketException
    	SendMessage(InetAddress to, int toPort) throws SocketException, UnknownHostException
    		{
    		// calls default constructor, assuming that YOU are the sender.
    
    		this(to, toPort, InetAddress.getLocalHost());
    		}// SendMessage(InetAddress to, int toPort) throws SocketException, UnknownHostException
    
    	public void send(Message message) throws IOException
    		{
    		// gets the socket from parent and calls the send method, sending
    		// a datagrampacket that is associated with the message being sent.
    
    		super.getSocket().send(message.getPacket());
    		}// public void send(Message message) throws IOException
    	}// public class SendMessage extends SendReceiveMessage
    
    	abstract class SendReceiveMessage
    		{
    		/**************************************************************************
    							SendReceiveMessage.java
    
    		This object models a datagram socket and is used for sending packets
    
    		methods:
    			SendReceiveMessage(InetAddress to, int port)
    				sets the datagramSocket given the IP and the Port number
    			public int getPort()
    				accessor for socket port number
    			public int getIP()
    				accessor for socket IP number
    			public DatagramSocket getSocket()
    				accessor for the datagram socket
    		**************************************************************************/
    
    		private DatagramSocket socket;
    
    		SendReceiveMessage(InetAddress to,int port) throws SocketException
    			{ this.socket = new DatagramSocket(port, to); }
    
    		public int getPort()
    			{ return socket.getPort(); }
    
    		public InetAddress getIP()
    			{ return socket.getInetAddress(); }
    
    		public DatagramSocket getSocket()
    			{ return socket; }
    		}// abstract class SendReceiveMessage
    
     
  2. samm

    samm Next in Line

    Joined:
    Dec 22, 2000
    Messages:
    2,629
    Likes Received:
    0
    Location:
    San Jose, CA
    Nice job. Looks like a great program. Any plans for a GUI?

    It compiled and ran on my computer running MacOS 10.2.6.
     
  3. Fantik

    Fantik Guest

    yes, my next iteration will be the GUI, and an easier way to configure the subnets of the network that need to be scanned for other users.
    (rather than editing the source and recompiling)
     
  4. Scn64

    Scn64 Guest

    All I have to say is :eek: :eek2: :eek3:

    :cool:
     
  5. Fantik

    Fantik Guest

    Question: How do you guys usually implement your GUI's. With an IDE (and if so, which one is your favorite) or just code it all manually.
     
  6. CompiledMonkey

    CompiledMonkey New Member

    Joined:
    Oct 26, 2001
    Messages:
    8,528
    Likes Received:
    0
    Location:
    Richmond, VA
    Code it manually. You get better results that way.
     

Share This Page