Hello there I am trying to develop a simple multithreaded chat server
but I am stuck.
Below ther are 3 separate classes that is are not inner classes of the
Server class.
What I d like to do is for the class Main to start the class
ChatHandler that continuosly listen for client requests to connect with
the class Server which creates an instance of it to handle the client
inputs, create and sends the appropriate output using the method run()
that calls the open() processRequests() and close() methods.
In the class ChatHandler inside the run() method the line code:
Thread aThread = new Thread(new Server(client));// ?????????
i cannot use the existing Server constructor as that would create a new
server's JFrame every time a client connects to the server.
Do I have to create a new Server class' constructor like,
public Server(Socket s)
{
...
}
or else?? Any suggestion??
//start of Server class
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server extends JFrame implements Runnable
{
....
//constructor for the Server
public Server(String title)
{
setSize(400, 400);
setTitle(title);
....
}
public void run()
{
try
{
while(true)
......
open();
processRequests();
close();
.....
}
//helper method for the class to set up the streams
private void open() throws IOException
{
....
}
//process the string received from each client and sends output to
clients
private void processRequests() throws IOException
{
String ....
}
//helper method to close the streams with each client
private void close() throws IOException
{
.....
}
}
//end of Server class
//start of ChatHandler class
import java.net.*;
import java.io.*;
public class ChatHandler
{
static final int PORT_NUMBER = 4000;
public ChatHandler()
{
}
public void run()
{
try
{
ServerSocket server = new ServerSocket(PORT_NUMBER);
while(true)
{
Socket client = server.accept ();
System.out.println ("Accepted from " +client.getInetAddress));
Thread aThread = new Thread(new Server(client)); //?????????????
aThread.start ();
}
}
catch(IOException e)
{
System.out.println("Trouble with ServerSocket, port
"+PORT_NUMBER +": " + e);
}
}
}
//end of ChatHandler class
//start of main class
public class Main
{
public static void main(String[] args)
{
ChatHandler cH = new ChatHandler();
cH.run();
}
}
//end main class
Cheers Pat
bherbst65@hotmail.com - 27 Aug 2005 00:06 GMT
Hi Pat010,
I came across this a while ago and it may give your some ideas that
you might want, but not not sure.
http://www.cise.ufl.edu/~amyles/tcpchat/
Bob