Here I am going to explain how to make Chat Conferencing program. This program uses the basic concepts of multithreading , networking.
You will have to writer separate program for both client and Server1. Chat Client :
Client Request the server for connection by sending hostname means name of server(IP Address of server) and the port number(port number identifies to which process of server the client want to connect to).
Here I have Used Socket class to send request to server to connect. After server accepts the connection from client, we can get input stream and o/p stream to send and receive data from server. To send and receive data simultaneously , we have to do multithreading to make program interactive. Here there is too thread , one is Main Thread which is created by JVM and another is created in this program.
//By Milan D Ashara
package client;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Client implements Runnable { //
public static Socket clientSocket = null;
public static PrintStream os = null;
public static DataInputStream is = null;
public static BufferedReader inputLine = null;
public static boolean closed = false;
public static void main(String[] args) {
int port_number = 0;
String host = "";
boolean flag = true;
if (args.length < 2) {
System.out.println("Please Enter Host name & port Number :");
while (flag) {
try {
System.out.println("Enter Host : ");
Scanner in = new Scanner(System.in);
host = in.next();
System.out.println("Enter port number :");
port_number = in.nextInt();
flag = false;
System.out.print("Server Initialized.");
} catch (InputMismatchException e) {
System.out
.println("Please enter port number in integer only :");
}
}
} else {
host = args[0];
port_number = Integer.valueOf(args[1]).intValue();
}
// connect to sever
try {
clientSocket = new Socket(host, port_number);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + host);
} catch (IOException e) {
System.err
.println("Couldn't get I/O for the connection to the host "
+ host);
}
if (clientSocket != null && os != null && is != null) {
try {
// Create a thread to read from the server
new Thread(new Client()).start();
// write data to server that sends it to user connected with
// server
while (!closed) {
System.out.println("Message :");
os.println(inputLine.readLine());
}
// Clean up:
// close the output stream
// close the input stream
// close the socket
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
public void run() {
String responseLine;
// Keep on reading from the socket till we receive the "Bye" from the
// server,
// once we received that then we want to break.
try {
while ((responseLine = is.readLine()) != null) {
System.out.println("From <"
+ clientSocket.getInetAddress().getHostName() + " > :"
+ responseLine);
if (responseLine.indexOf("*** Bye") != -1)
break;
}
closed = true;
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
2. Chat server
Server continuously listens the client and accepts the connection. Once server accepts the connection , server has to sense the input stream of all client and forward the received message to all client except the sender client.2.1) Server.java
Here I have used ServerSocket class that listens the client on a particular port number. Once it receives the client request it accepts the connection and create the new thread. Each new thread per client request will contain input and output stream of all client. All new Thread will continuously sense the input stream. If there is any data it forwards means to output using output stream to all other client except itself.
package server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Server {
public static Socket clientSocket = null;
public static ServerSocket serverSocket = null;
public static ArrayList<ClientThread> clientList = new ArrayList<ClientThread>();
public static void main(String[] args) {
int port_number = 0;
boolean flag = true;
if (args.length < 1) {
System.out.println("Please Enter Port Number :");
while (flag) {
try {
Scanner in = new Scanner(System.in);
port_number = in.nextInt();
flag = false;
System.out.print("Server Initialized.");
} catch (InputMismatchException e) {
System.out
.println("Please enter port number in integer only :");
}
}
} else {
port_number = Integer.valueOf(args[0]).intValue();
System.out.print("Server Initialized.");
}
// open server socket on port number
try {
serverSocket = new ServerSocket(port_number);
} catch (IOException e) {
System.out.println(e);
}
// accept connections
while (true) {
try {
clientSocket = serverSocket.accept();
ClientThread ct = new ClientThread(clientSocket, clientList);
clientList.add(ct);
ct.start();
} catch (IOException e) {
System.out.println(e);
}
}
}
}
2.2) ClientThread.java
package server;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;
class ClientThread extends Thread {
DataInputStream is = null;
PrintStream os = null;
Socket clientSocket = null;
ArrayList<ClientThread> clientList;
ClientThread(Socket clientSocket, ArrayList<ClientThread> clientList) {
this.clientSocket = clientSocket;
this.clientList = clientList;
}
public void run() {
String msg = "";
try {
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
// name = is.readLine();
os.println("Hello " + this.clientSocket.getInetAddress()
+ " to our chat room.\nTo leave enter /quit in a new line");
for (int i = 0; i < clientList.size(); i++)
if (clientList.get(i) != null && clientList.get(i) != this)
clientList.get(i).os.println("*** A new user "
+ this.clientSocket.getInetAddress()
+ " entered the chat room !!! ***");
while (true) {
msg = is.readLine();
if (msg.startsWith("/quit"))
break;
for (int i = 0; i < clientList.size(); i++)
if (clientList.get(i) != null & clientList.get(i) != this)
clientList.get(i).os.println("<"
+ this.clientSocket.getInetAddress() + "> "
+ msg);
}
for (int i = 0; i < clientList.size(); i++)
if (clientList.get(i) != null && clientList.get(i) != this)
clientList.get(i).os.println("*** The user " + this.clientSocket.getInetAddress()
+ " is leaving the chat room !!! ***");
os.println("*** Bye " + this.clientSocket.getInetAddress() + " ***");
// Clean up:
// Set to null the current thread variable such that other client
// could
// be accepted by the server
clientList.remove((ClientThread)this);
/*for (int i = 0; i <= 9; i++)
if (t[i] == this)
t[i] = null;*/
// close the output stream
// close the input stream
// close the socket
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
}
;
}
}
Enjoy Network Messenger……!
No comments:
Post a Comment