Simple Chat Server Example
A) ChatServer
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ChatServer{
/* Instance variables declared as static are, essentially, global variables. When objects of
its class are declared, no copy of a static variable is made. Instead, all instances of the
class share the same static variable. */
private static ServerSocket serversock;
private static int port = 1234;
/*** main() ***/
public static void main(String args[]){
System.out.println("\n *** ChatServer ***\n");
System.out.println("Server Opening port "+port+" ...\n");
try{
/*Creating s 'ServerSocket' object */
serversock = new ServerSocket(port);
}
catch(IOException ioe){
System.out.println("IOException occuted : "+ioe);
System.exit(1);
}
do{
handleClient();
}while(true);
}//main end
/*** handleClient() ***/
/* private static method means you can not invoke the method from
outside the class as the method is private to the class. */
/* Methods declared as static have several restrictions:
1.They can only call other static methods.
2.They must only access static data.
3.They cannot refer to this or super in any way.
A static method can access only the static features, static methods,
and static variables of its parent class. */
private static void handleClient(){
Socket clientsock = null;
try{
System.out.println("Server Lisening to port: "+port+"...\n");
/* The server waits indefinitely ('blocks') for a client to connect. It does this by calling
method accept of class 'ServerSocket', which returns a 'Socket' object(client object) when a
connection is made.This create a communication link between Server and Client.
This connection between server and client remains open throughout
the duration of the dialogue between the two and is only broken (under normal
circumstances) when one end of the dialogue formally terminates the exchanges (via
an agreed protocol). */
clientsock = serversock.accept();
/*'Printwriter' and 'Scanner' objects for sending and receiving data from client.
The 'Scanner' object at the client end will receive messages sent by the 'PrintWriter'
object at the server end, while the 'PrintWriter' object at the client end will send
messages that are received by the 'Scanner' object at the server end (using methods
'nextLine' and 'println' respectively).Supplying the PrintWriter constructor with a
second argument of true will cause the output buffer to be flushed for every call of
println (which is usually desirable).*/
Scanner input = new Scanner(clientsock.getInputStream());
PrintWriter output = new PrintWriter(clientsock.getOutputStream(),true);
/*Message counter*/
int numMessage = 0;
System.out.println("1Server waiting for client's message");
/*receving message from client*/
String message = input.nextLine();
while(!message.equals("CLOSE"))
{
System.out.println("One Message Received\n");
/*sending message to client*/
numMessage++;
output.println("Message "+numMessage+" : "+message);
System.out.println("2Server waiting for client's message");
message = input.nextLine();
}
/*sending message to client*/
output.println(numMessage+" Message Received\n");
}
catch(IOException ioe){
System.out.println("IOException occuted : "+ioe);
System.exit(1);
}
finally{
try{
System.out.println("\nClosing Connection");
clientsock.close();
}
catch(IOException ioe){
System.out.println("IOException occuted : "+ioe);
System.exit(1);
}
}//finally
}//handleClient()end.
}//
/* When a member is declared static, it can be accessed before any objects of its class are created,
and without reference to any object. You can declare both methods and variables to be static. */
/* All of the static statements(including staic blocks) are run(executed) only once,when your program
begins execution (or,more precisely, when its class is first loaded).*/
*************************************************************************
B) ChatClient
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ChatClient{
/* Instance variables declared as static are, essentially, global variables. When objects of
its class are declared, no copy of a static variable is made. Instead, all instances of the
class share the same static variable. */
private static int port = 1234;
/*** main() ***/
public static void main(String args[]){
System.out.println("\n *** ChatClient *** \n");
accessServer();
}//main end
/*** accessServer() ***/
/* private static method means you can not invoke the method from
outside the class as the method is private to the class. */
/* Methods declared as static have several restrictions:
1.They can only call other static methods.
2.They must only access static data.
3.They cannot refer to this or super in any way.
A static method can access only the static features, static methods,
and static variables of its parent class. */
private static void accessServer(){
Socket clientsock = null;
try{
clientsock = new Socket("localhost",port);
/*The 'Scanner' object at the client end will receive messages sent by the 'PrintWriter'
object at the server end, while the 'PrintWriter' object at the client end will send
messages that are received by the 'Scanner' object at the server end (using methods
'nextLine' and 'println' respectively).Supplying the PrintWriter constructor with a
second argument of true will cause the output buffer to be flushed for every call of
println (which is usually desirable).*/
Scanner input = new Scanner(clientsock.getInputStream());
PrintWriter output = new PrintWriter(clientsock.getOutputStream(),true);
/*client program will need to set up an input stream
(as another Scanner object) to accept user messages from the keyboard.*/
Scanner userEntry = new Scanner(System.in);
String message,response="dd";
do{
System.out.println("Enter Message: ");
/*Accepting user messages from the keyboard*/
message = userEntry.nextLine();
/*sending messages to the Server*/
output.println(message);
/*receiving response messages from the Server*/
response = input.nextLine();
/* printing response in client*/
System.out.println("SERVER> "+response);
}while(!message.equals("CLOSE"));
}//try
catch(IOException ioe){
System.out.println("IOException occured: "+ioe);
}
finally{
try{
System.out.println("Closing Connection\n");
clientsock.close();
}
catch(IOException ioe){
System.out.println("IOException occured: "+ioe);
}//try
}//finally
}//accessServer()end.
}
By SAJU.M
****************************************************************************
No comments:
Post a Comment