Link to home
Start Free TrialLog in
Avatar of xannus
xannusFlag for United States of America

asked on

Java Chat code - from bare basics

Hi experts

I am having trouble getting a very simple chat skeleton going.
I am going from step 0;
I have tried using the public code available, but I want to do the structure myself, from scratch, so I can understand it. In the attached txt, are two classes, (client) and (server) that I have started to fill out..

I am stuck on one point right now. Both the client and server will do their work in a run() method
See where I do the new Server ... in the void main ?
Even though it is an empty constructor (for now), the threads still get knotted up, and I cant see why? One is an accept() and the other is quick sleep and println()
Does an accept() in one thread mess other Threads up?

Plz see two classes code in attached .txt (wont upload zip files)
Jserver4experts.txt.txt
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Try the following to start the client and server. They will be run in separate threads
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new JServer().start();
        new JClient().start();
    }

Open in new window

Something like the following should be OK for the client:
    public void run() {
        try {
            Thread.sleep(1000);
	    Socket s = new Socket("localhost", 1234);
	    Scanner in = new Scanner(s.getInputStream());
	    while(in.hasNext()) {
		System.out.println(in.nextLine());
	    }
	    in.close();
	    s.close();
            System.out.println("JClient run() ");
        } catch (Exception e) {
            System.out.println("run() excep: " + e);
        }
    }

Open in new window

Avatar of xannus

ASKER

** Thx all **

With the constructors and accept Thread now lined up and working, what would the code be like for a JFrame that can receive and send chat data? In a dataoutputstream?

Decouple what you have from the gui by sending events containing the chat strings and adding the gui as a listener
Avatar of xannus

ASKER

Thx All

I have patched together all of your combined suggestions into a "final"  attempt at the JClient and JServer startoff. (attached)

By final, I mean good as a solid starting off point to begin a network chat/game java framework.
It is printf happy right now.
All that needs to be done from here is to design a JFrame interface, game objects or chat interface. and atttach the necessary sockets and streams to each item.
........
Speaking of which,
I am considering scrapping the all text system (for my game) and using a dataoutputstream that sends Structs/Objects/holders that contain all data members possible for any message.
This would include chat items, in game movement, etc.
I doubt it, but is there anything I have overlooked in the attached code? considering I may want to bullet-proof it later.
?
Thanks
JServer4experts2.txt.txt
The main thing you need to go is to get it multi-threaded. You need to handle each incoming connection in a separate thread
Avatar of xannus

ASKER

Thx,
That is what my framework does, doesnt it?


JClient is a Thread.
I have an array of all the sockets

Once I fill in the run() method, it should all be set up well? Server -> client
?
No - your multithreading so far is there to run the client and server in the same vm - something of course that wouldn't happen in a 'real' C/S application.

The multithreading i'm referring to should exist at the server to allow more than one client to connect. In a single threaded model, a new connection cannot be made until the previous client has been fully serviced
Avatar of xannus

ASKER

Right..
So, an accept()ed client needs to be passed to a Handler thread of some kind?
one new Handler(socket) for each connection? (a list of Handlers)
so the accept() loop thread carries on? without missing a step.

Something on the lines of?...

private static class Handler extends Thread {
        private String name;
        private Socket socket;
        private BufferedReader in;
        private PrintWriter out;

....
?

>>So, an accept()ed client needs to be passed to a Handler thread of some kind?

Exactly right. Implementing Runnable is more flexible than extending Thread though. You can pass the Socket to the ctor of the handler
Avatar of xannus

ASKER

I've seen that a bit recently (implementing Runnable). Should I give up on extending Thread, then?
What does "more flexible" mean? Is this maybe related to VM implementation?
Any worst case examples? Different Threads fighting eachother?
It's just a question of convenience. One example would be inheritance: java doesn't support multiple implementation inheritance, only single inheritance, so once you've extended Thread, you've used up your quota
Take a look at the following for a way to create a multi-threaded server. If you use that as your basis, you only need to provide implementations of the Service interface:

http://technojeeves.com/joomla/index.php/free/84-server-by-david-flanagan
Avatar of xannus

ASKER

CEHJ, I like the Service angle. TY
Very appealing.

With this multi-server, does the server notify every service? or only one (I might make that one service notify the others, but that would be very inefficient) How might I make the Server broadcast input to every attached Service,
assuming I make that Service a chat window / or game client.

There's no broadcast element involved here, since each service is designed to be independent.

I think you should probably look into Java software that's more directly related to chat, e.g. an XMPP server
Avatar of xannus

ASKER

Great XMPP link,

however, I'm more interested in Java code, maybe 2 classes - A multiserver class and a Client class/interface.
I titled the question with chat code, because I knew if I got code for a multi-server chat, I could message it into what I need for a game server (RTS)
Should I del this question and ask for RTS server code?
I'm going to have another look at the Flanagan code myself later. I can't remember if it's possible to have contextual info in each Service. If that can be done, then it should be quite possible for Service-state info to be retained, which should allow broadcasting and perhaps some coupling
Avatar of xannus

ASKER

Any luck?
Should be possible. Have a look at the Control class - of necessity it coordinates clients and server so it should be possible to use something like this to coordinate chat clients too
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of xannus

ASKER

Great code. Thanks
Funny that he's doing exactly what i suggested ;-)