1 Replies - 4384 Views - Last Post: 20 August 2011 - 10:38 AM Rate Topic: -----

#1 csharpbacha  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 67
  • Joined: 18-March 10

Steps required in making a simple chat application in Java

Posted 20 August 2011 - 09:18 AM

I know that to make a chat application in java i need to understand Multithreading and Networking. What i can't find out is what steps are to be implemented? i mean, i know there has to be at least 2 threads (listening and one printing). what else is required?
Is This A Good Question/Topic? 0
  • +

Replies To: Steps required in making a simple chat application in Java

#2 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1150
  • View blog
  • Posts: 2,528
  • Joined: 05-May 05

Re: Steps required in making a simple chat application in Java

Posted 20 August 2011 - 10:38 AM

Here's a tutorial on server/client apps. The only problem I foresee using two threads is that you'll have to use non-blocking I/O. If one thread is listening for all client input using sockets, all clients will starve. e.g.

ReceptionThread rt = new ReceptionThread();
new Thread(rt).start();
while(true) {
	Socket client = serverSocket.accept();
	rt.addSocket(client);
}



class ReceptionThread implements Runnable {
	List<Socket> clientSockets;
	public void run() {
		while(serverIsActive) {
			BufferedReader bf;
                        //poll each client socket 
			for(int i = 0; i < clientSockets.size(); i++) {
				bf = new BufferedReader(new InputStreamReader(clientSockets.get(i).getInputStream()));
				String msg;
                                //Oh No! blocks until msg arrives
				if((msg = bf.readLine()) != null) { 
					broadcast(msg);
				}
			}
		}
	}
	void addSocket(Socket s) {
		clientSockets.add(s);
	}
}



Quote

For nonblocking IO don't use InputStream and Reader (or OutputStream/Writer), but use the java.nio.* classes, in this case a SocketChannel (and additional a CharsetDecoder).
~ Java NIO discussion


If you don't want to use NIO to write your application, consider spawning a new thread for each client. That way, blocking streams will only affect it's enclosing thread.

while(true) {
	Socket client = serverSocket.accept();
	ClientThread ct = new ClientThread();
	ct.clientSocket = client;
	new Thread(ct).start();
}



class ClientThread implements Runnable {
	Socket clientSocket;
	public void run() {
		BufferedReader bf = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		while(serverIsActive) {
			String msg;
                        //poll one socket; who cares if the I/O blocks
			if((msg = bf.readLine()) != null) { 
				broadcast(msg);
			}
		}
	}
}



Maybe you can do this without NIO and two threads, but I cant think of a way to.

This post has been edited by blackcompe: 20 August 2011 - 10:41 AM

Was This Post Helpful? 2
  • +
  • -

Page 1 of 1