954,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Java Chat "Help"

I am trying to get the ST.java (Server Thread) to communicate with the CT.java (Client Thread), i am stuck at this point, i dont know rather it is something to do with the port # and host, or if it has anything to do with the Server thread, please reply thanks.

[TEX]CT.java Client Thread File[/TEX]

<pre><code>&lt;code&gt;import javax.swing.*;
import java.awt.*; 
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.net.*;
import java.io.*;

class ClientThread extends Thread
{
	JTextArea ta1, ta2;

	static final String newline = System.getProperty(&amp;quot;line.separator&amp;quot;);

	public ClientThread(String str, JTextArea t1)
	{
		super(str);
		ta1 = t1;
	}

	String m_strHost = &amp;quot;&amp;quot;;
	String m_strMsg = &amp;quot;&amp;quot;;
	int m_nPort = -1;

	//public static void main(String arg[])
	//{
	//    int[] a;
	//    a = new int[100];
	//    //ClientThread ct = new ClientThread(arg[0], arg[1], arg[2]); //The Client thread requires three arguments to run
	//    //ct.start(); // Client Thread starts here
	//}

	public ClientThread() 
	{ 
		super(&amp;quot;client&amp;quot;);
		initThread(&amp;quot;CU-109JST11&amp;quot;, &amp;quot;7236&amp;quot;, &amp;quot;test&amp;quot;); //Arguments are passed to ClientThread
		
	}

		public void initThread(String host, String port, String msg) 
		{
			
			m_strHost = host; 
			m_strMsg = msg; 
			try
			{
				m_nPort = Integer.parseInt(port);
			}
			catch (Exception e) { m_nPort = 7236; }
		}

		public void run()
		{
			int i = 0;
			while (true)
			{
				SendMessage(m_strMsg);
				try
				{
					sleep(3000);
				}
				catch (Exception e)
				{
				}
			}
		}

		protected void SendMessage(String message)
		{
			Socket client = null;
			DataOutputStream output = null;

			try
			{
				client = new Socket(m_strHost, m_nPort);
			}
			catch (UnknownHostException e)
			{
				return;
			}
			catch (IOException e)
			{
				return;
			}
			try
			{
				output = new DataOutputStream(client.getOutputStream());
			}
			catch (IOException e)
			{
				return;
			}

			try
			{
				output.writeBytes(message);
			}
			catch (IOException e)
			{
				return;
			}

			try
			{
				output.flush();
			}
			catch (IOException e)
			{
				return;
			}

			try
			{
				if (client != null)
				{
					client.close();
				}
			}
			catch (IOException e)
			{
			}
		}
}

public class CT extends JApplet //Java Applet is created
{
	DrawPanel Prompt; // The DrawPanel is an instance of JPanel, Prompt is an instance of DrawPanel

	public void init()
	{
		//Execute a job on the event-dispatching thread:
		//creating this applet's GUI.
		try
		{
			javax.swing.SwingUtilities.invokeAndWait(new Runnable()
			{															//The Original System code is transformed to an Applet based code
				public void run()
				{
					createGUI(); //Creation of GUI
				}
			});
		}
		catch (Exception e)
		{
			System.err.println(&amp;quot;createGUI didn't successfully complete&amp;quot;); // !!Error Message of failed attempt to run applet
		}
	}

	public void createGUI() //The GUI is Created
	{

		//Container c = getContentPane();

		add(Prompt = new DrawPanel(), BorderLayout.CENTER); //Adding Prompt to the center 

		JTextArea ta1 = new JTextArea(10,10); //A text area is created for sending and messages
		add(ta1, BorderLayout.CENTER); //The Text Area is added and Centered

		new ClientThread(&amp;quot;client&amp;quot;, ta1).start();

		setSize(400, 220);  //Size of frame is 400 x 220 pixels
		setVisible(true);


		
	}

	public static void main(String[] args) 
	{
		CT hws = new CT();  //instantiate this class

	}
}&lt;/code&gt;</code></pre>


.[TEX]ST.java Server Thread File::::::::::::::::::::::::::::::::::::::::::::::::::[/TEX]

<pre><code>&lt;code&gt;import javax.swing.*;
import java.awt.*; 
import java.net.*;
import java.io.*;

/**
 * A simple server - it listens to incoming messages at a specific port number
 */
class ServerThread extends Thread
{

	JTextArea ta1, ta2;

	static final String newline = System.getProperty(&amp;quot;line.separator&amp;quot;);

	public ServerThread(String str, JTextArea t1, JTextArea t2)
	{
		super(str);
		ta1 = t1;
		ta2 = t2;
		initThread(&amp;quot;7236&amp;quot;); //Arguments are passed to ClientThread
	}

	Socket client = null;	//socket through which to communicate to the client
	ServerSocket server;	//the server socket
	DataInputStream input = null;	//an input stream to receive incomming messages
	MessageThread mt = null;//a thread to handle individual communications
	
	/**
	 * The constructor
	 * port - the port number to listen to
	 */
	public ServerThread() 
	{ 
		super(&amp;quot;client&amp;quot;);
		initThread(&amp;quot;7236&amp;quot;); //Arguments are passed to ClientThread
		
	}

	public void initThread(String port)
	{
		try
		{
			int answer = Integer.parseInt(port);//try to get the port number			
			server = new ServerSocket(answer);	//instantiate a new socket object
			answer = server.getLocalPort();		//get the local port in case our wanted port is not available
			ta1.append(&amp;quot;Server waiting :&amp;quot;);
		} 
		catch (Exception e) { }
	}
	/**
	 * The active component of the thread class
	 */
	public void run()
	{
		//listen for incoming client requests forever until stopped
		while(true)
		{
			try
			{
				if ( server != null )
				{
					client = server.accept(); //if a client requests a connection accept it
				}
				else {	break;	}
			}
			catch (IOException e)
			{
				ta1.append(&amp;quot;unable to accept client request&amp;quot;);
				continue;
			}
			
			//if connection was established then try to read the message coming from the
			//client using this thread
			mt = new MessageThread(this, client);
			mt.start();
		}
	}
	
	/**
	 * Starts the server and listen at a specific port
	 * arg[0] - the port number to listen to
	 */
	//public static void main(String arg[])
	//{
	//    ServerThread st = new ServerThread(arg[0]);
	//    st.start();
	//}	
}

/**
 * A simple thread to read client messages
 */
class MessageThread extends Thread
{

	JTextArea ta1, ta2;

	static final String newline = System.getProperty(&amp;quot;line.separator&amp;quot;);

	public MessageThread(String str, JTextArea t1, JTextArea t2)
	{
		super(str);
		ta1 = t1;
		ta2 = t2;

	}

	protected ServerThread parent;	//the reference to the server 
	protected Socket client;		//the socket connected to the client
	BufferedReader d;				//a buffer to collect the characters send by the client
	BufferedWriter dOut;

	/**
	 * The constructor
	 */
	public MessageThread(ServerThread p, Socket c)
	{
		super(&amp;quot;MessageThread&amp;quot;);	//call the constructor of our parent class
		parent = p;				//save the parent for later
		client = c;				//save the client for later
	}

	/**
	 * The avtive component of this thread class
	 */
	public void run()
	{
		String message = &amp;quot;&amp;quot;;			//an object to store the message
		DataInputStream input = null;	//an input stream to receive client messages
		DataOutputStream output = null;
		
		try
		{
			input = new DataInputStream(client.getInputStream());//try to get the input stream
			d = new BufferedReader(new InputStreamReader(input));//try to create the buffer

		}
		catch (IOException e)
		{
			return;
		}
		
		try
		{
			output = new DataOutputStream(client.getOutputStream());//try to get the input stream
			//dOut = new BufferedWriter(new OutputStreamWriter(output));//try to create the buffer

		}
		catch (IOException e)
		{
			return;
		}
		
		try
		{
			String temp = d.readLine();	//read the message client sent
			//System.out.print((char) 0x07);
			System.out.println(temp);	//print it to the console
			input.close();				//close the input stream
			//dOut.write(&amp;quot;Server Says: &amp;quot;+temp);
			ta2.append(&amp;quot;Server Says: &amp;quot; + temp);
			//d.close();					//close the buffer
			output.flush();
			output.close();
			client.close();				//close the client socket				
		}
		catch (IOException e)
		{
			return;
		}
	}
}

public class ST extends JApplet
{
	DrawPanel Prompt;

	public void init()
	{
		//Execute a job on the event-dispatching thread:
		//creating this applet's GUI.
		try
		{
			javax.swing.SwingUtilities.invokeAndWait(new Runnable()
			{
				public void run()
				{
					createGUI(); //Creation of GUI
				}
			});
		}
		catch (Exception e)
		{
			System.err.println(&amp;quot;createGUI didn't successfully complete&amp;quot;); // !!Error Message of failed attempt to run applet
		}
	}

	public void createGUI()
	{



		//Container c = getContentPane();


		System.out.println(&amp;quot;skdaj&amp;quot;);
		//add(Prompt = new DrawPanel(), BorderLayout.CENTER); //Adding Canvas to the center

		JTextArea ta1 = new JTextArea(7,10);

		JTextArea ta2 = new JTextArea(10,10);
		add(ta1, BorderLayout.NORTH);
		add(ta2, BorderLayout.SOUTH);

		new ServerThread(&amp;quot;client&amp;quot;,ta1, ta2).start();
		new MessageThread(&amp;quot;client&amp;quot;, ta1, ta2).start();

		setSize(350, 275);
		setVisible(true);



	}

	public static void main(String[] args)
	{
		ST hws = new ST();  //instantiate this class

	}
}&lt;/code&gt;</code></pre>
bpushia
Newbie Poster
5 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You