Saturday 16 July 2011

Fairy Chat server



SOURCE CODE FOR FAIRYCHAT APPLICATION


Listing 1 is source code for FairyChatserver. The source code contains the coding to store the port on which the will listen for new connections. The chat server attempts to create a new server socket and begin to accept connections. First, a new ServerSocket object is created with a specific port. The code then enters an endless loop, continuously accepting connections and creating new chat client . The ServerSocket.accept() method waits forever until a new connection is established. When a new connection is detected, a Socket object is created inherently and returned. A new ClientConnetcion object is then constructed with the newly created socket. Since the ClientConnection is a Thread, we must call the start method to make the chat client code run.
To run the server, the users have to save the source code in java bin as “FairyChatServer.java”. Then the users have to compile in the command prompt.

LISTING 1
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class FairyChatServer
{
// public FairyChatServer (int port) throws IOException ...
// public static void main (String args[]) throws IOException ...

public FairyChatServer () throws IOException
{
ServerSocket serverSocket = new ServerSocket (2000);
// The above statement is the ServerSocket class and its object serverSocket, which
// listen's for the port Number.

while (true)

// Here the above statement while loop which is ready to continuously listen for the
// client connection.

{
Socket client = serverSocket.accept ();

// The above statement get the client's socket.

System.out.println ("Accepted from " + client.getInetAddress ());

// Above statement get the Inet Address of each client.

ClientsConnections cCon = new ClientsConnections (client);
cCon.start ();
}
}


public static void main (String args[]) throws Exception
{
new FairyChatServer ();
}

}

class ClientsConnections extends Thread
{
protected Socket socket;
protected DataInputStream dti;
protected DataOutputStream dto;
static String selFont,selStyle,sendStr;
static int selSize;

public ClientsConnections (Socket s) throws IOException
{
this.socket = s;
dti = new DataInputStream (new BufferedInputStream (s.getInputStream ()));
dto = new DataOutputStream (new BufferedOutputStream (s.getOutputStream ()));
}

protected static Vector clientConnections = new Vector ();

public void run ()
{
try {
clientConnections.addElement (this);
while (true)
{
String msg = dti.readUTF ();
/* int i,li,starti,startli,end,chs;
String sub,sub1;
i=msg.indexOf(">");
starti=i+1;
li=msg.lastIndexOf(">");
startli=li+1;
sub=msg.substring(starti);
int subi=sub.length();
int start=0;
end=subi-3;
char ch[]=new char[end-start];
sub.getChars(start,end,ch,0);
sub1=msg.substring(startli);
String getCh=new String(ch);
selFont=new String(getCh);
int geNum=Integer.parseInt(sub1);
selSize=geNum;
int st,endStr;
st=0;
endStr=i;
char chrs[]=new char[endStr-st];
msg.getChars(st,endStr,chrs,0);
String getChs=new String(chrs);
sendStr=new String(getChs);*/
broadcast (msg);
}
} catch (IOException ex)
{
System.out.println(socket.getInetAddress()+" Client has been closed Connection...");
} finally
{
clientConnections.removeElement (this);
try
{
socket.close ();
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}

// protected static void broadcast (String message) ...

protected static void broadcast (String message)
{
synchronized (clientConnections)
{
Enumeration e = clientConnections.elements ();
while (e.hasMoreElements ())
{
ClientsConnections cTypecast = (ClientsConnections) e.nextElement ();
try
{
synchronized (cTypecast.dto)
{
cTypecast.dto.writeUTF (message);
}
cTypecast.dto.flush ();
} catch (IOException ex)
{
cTypecast.stop ();
}
}
}
}
}

Listing 2 is source code to open the chat window for client to chat. The source code contains layout of Login window to log into the chat application such as user name, user password, start button and cancel button in UserFrame( ). Then next part of source code part contains the layout of the chat applet with certain main function to run the application. To run the chat applet the user have to save the source code in java bin as ClientWindow.java. Then user have to compile in command prompt in order to open the chat window applet and start chatting.

LISTING 2
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;


public class ClientWindow
{
public static void main(String args[])
{
Frame userFrame=new UserFrame();
userFrame.setTitle("Login Chat !");
userFrame.setSize(150,250);
userFrame.show();
}
}

class UserFrame extends Frame implements ActionListener
{
Frame chatClient;
Label nameLabel,passLabel,serverLabel;
TextField userText,passText,serverText;
Button startButton,cancelButton;

UserFrame()
{
setLayout(new FlowLayout(FlowLayout.LEFT));

nameLabel=new Label("User Name : ");
passLabel=new Label("Password : ");
serverLabel=new Label("Server Name : ");
userText=new TextField(15);
passText=new TextField(15);
passText.setEchoChar('*');
serverText=new TextField(15);
startButton=new Button("Start");
cancelButton=new Button("Cancel");
add(nameLabel);add(userText);

add(passLabel);add(passText);
add(serverLabel);add(serverText);
add(startButton);add(cancelButton);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

startButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
try
{
String uName,sName;
uName=userText.getText();
sName=serverText.getText();
Socket socket=new Socket(sName,2000);
chatClient=new

ChatClient1(socket,uName,sName,socket.getInputStream(),socket.getOutputStream());
chatClient.setTitle(uName+" : ChatWindow!");
chatClient.setSize(400,270);
chatClient.show();

}catch(Exception exp)
{}
}
}
class ChatClient1 extends Frame implements Runnable
{
protected DataInputStream dti;
protected DataOutputStream dto;
Socket socket;
protected TextArea dispMessage;
protected TextField sendMessage;
protected TextField input,uName;
protected Button sendButton;
protected Label selectColor,selectFont;
protected Choice choiceColor,choiceFont,choiceSize;
String userName;
String s;
String selFont,selStyle;
int selSize;
protected Thread listener;

public ChatClient1 (Socket socket,String userName,String serveName,InputStream

is,OutputStream os)
{
this.userName=userName;
dti=new DataInputStream(new BufferedInputStream(is));
dto=new DataOutputStream(new BufferedOutputStream(os));

setLayout (new FlowLayout(FlowLayout.LEFT));
setBackground(Color.blue);
setForeground(Color.black);
dispMessage=new TextArea(8,50);
selectColor=new Label("Colors ");
selectFont=new Label(" Font ");
choiceColor=new Choice();
choiceFont=new Choice();
choiceSize=new Choice();

GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames=ge.getAvailableFontFamilyNames();
for(int i=0;i<fontNames.length;i++)
choiceFont.add(fontNames[i]);
String sizeFont;
for(int i=8;i<=100;i++)
{
sizeFont=Integer.toString(i);
choiceSize.add(sizeFont);
}

uName=new TextField(userName,15);
sendMessage=new TextField(45);
sendButton=new Button("Send");

add(uName);
add(dispMessage);
add(selectColor);add(choiceColor);
add(selectFont);add(choiceFont);add(choiceSize);
add(sendMessage);add(sendButton);
sendMessage.requestFocus ();
uName.setEditable(false);
dispMessage.setEditable(false);
listener=new Thread(this);
listener.start();

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});


}



public void run ()
{
try {
while (true)
{
String line = dti.readUTF ();
dispMessage.appendText (line + "\n");
}
} catch (IOException ex)
{
ex.printStackTrace ();
} finally
{
listener = null;
sendMessage.hide ();
validate ();
try
{
dto.close ();
} catch (IOException ex)
{
ex.printStackTrace ();
}
}
}
public boolean handleEvent (Event e)
{
if ((e.target == sendMessage) && (e.id == Event.ACTION_EVENT))
{
try
{
dto.writeUTF (userName+" : "+(String) e.arg);
dto.flush ();
} catch (IOException ex)
{
ex.printStackTrace();
listener.stop ();
}
sendMessage.setText ("");
return true;
}
else if ((e.target == sendButton) && (e.id == Event.ACTION_EVENT))
{
try
{
s=userName+" : "+sendMessage.getText();
dto.writeUTF (s);
dto.flush ();
} catch (IOException ex)
{
ex.printStackTrace();
listener.stop ();
}
sendMessage.setText ("");
return true;

} else if ((e.target == this) && (e.id == Event.WINDOW_DESTROY))
{
if (listener != null)
listener.stop ();
hide ();
return true;
}
else if((e.target == choiceSize) && (e.id == Event.ACTION_EVENT))
{
String selsStr;
selsStr=choiceSize.getSelectedItem();
selSize=Integer.parseInt(selsStr);
return true;
}
else if((e.target == choiceFont) && (e.id == Event.ACTION_EVENT))
{
selFont=choiceFont.getSelectedItem();
return true;
}

return super.handleEvent (e);
}
}



USER MANUAL


To Use system


System Requirements

Operating System: Windows* 98/Me/2000/XP
Processor: Pentium* III 800 MHz or any affordable processor
Memory: 128 MB RAM (256 MB RAM Recommended)
Software: 1) j2sdk1.4.2_15 (77.3 MB size)
2) Command prompt
3) Notepad
Misc. Hardware: Keyboard and mouse (compatible with PC or laptop)



INSTRUCTION


  1. Start Windows* 98/Me/2000/XP.
  2. Copy FairyChatServer and ClientWindow source code in notepad and save it in java bin according to the class name .
  3. Open command prompt and compile FairyChatServer.java
  4. Then Open a different command prompt an compile ClientWindow.java.
  5. Once the Chat window open, user may start to chat.

Step 1:
Compile FairyChatServer.java in Command prompt










Step 2:
Compile ClientWindow.java in Command prompt















Step 3:
Key in User name ,Password and server name in login Applet once it appear after compiling ClientWindow.java


















Step 4:
Click the Start button to log in.

Step 5:
User may start chat once the Chatwindow appear.





















Step 6:
To send the text .User may enter the text in text box and click send to send the text to other user and wait for the reply from other user.




















Step 7:
To exit the Chat room, user has to click the close button to exit


so guys who want to have their own chat server in college or among freinds. Can use this chat applications.

No comments:

Post a Comment