Sie sind auf Seite 1von 20

1

INTRODUCTION:
Chatting has become a daily activity among humans in this modern age. Sending messages and receiving messages through a network or server is called chatting. For assignment, I have created a simple Chat application using java coding as its platform and I have called the chat application as Fairy Chat Application. User can use this chat application to chat with their friend for fun or to create a network among them and communicate through the application. For those that have became bored with talking with phone or oral and for those who wanted to communicate in different way. This Fairy Chat Application is an answer for them. The Fairy chat application system presented here consists of two classes: FairyChatServer and ClientWindow. The FairyChatServer class is responsible for accepting connections from clients and providing each client with a dedicated thread for messaging. The ClientWindow is an extension of class Thread. This class is responsible for receiving client messages and broadcasting those messages to other clients.

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;

4 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) ...

5 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 !");

6 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 {

7 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);

8 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 {

10 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); } }

11

USER MANUAL
To Use system
System Requirements Operating System: Processor: Memory: Software: Misc. Hardware: Windows* 98/Me/2000/XP Pentium* III 800 MHz or any affordable processor 128 MB RAM (256 MB RAM Recommended) 1) j2sdk1.4.2_15 (77.3 MB size) 2) Command prompt 3) Notepad 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.

12

Step 1: Save FairyChatServer.java

13

14

Step 2: Save ClientWindow.java

15

16

Step 3: Compile FairyChatServer.java in Command prompt

17

Step 4: Compile ClientWindow.java in Command prompt

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

Step 6: Click the Start button to log in.

18

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

Step 8: 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 9: To exit the Chat room, user has to click the close button to exit.

19

LIMITATION:
Although, Fairy Chat Application is running, it still face some of limitation. This limitation have make the chat application a bit low in performance. Fairy Chat application system limitation are: 1) User cant change the font colors even though a combo box is given. 2) User cant change the font size even though a combo box is given. 3) Users only can chat in main chat room. There is no private room for the user to chat personally. 4) There is no icon in the applet. 5) The font will not change after the changing it into different font. 6) User cant change the background colors.

RECOMMENDATIONS:
Every limitation can be overcome by a solution. Same goes to the limitation of Fairy Chat application. It can be overcome. In future would I have, to create a better chat application system which will allow users to: 1) 2) 3) 4) 5) 6) 7) 8) Change the Font. Change the Font Size Change The Font Colors Change the background colors Send icon Send animation icon. Send sound effect Chat in private room.

20

CONCLUSION: After finishing my assignment, I came to know more well about java GUI application. This assignment have given a opportunity to level up my ability and skills in designing simple chat application using java as my platform. After finishing the assignment I gain more ideas to develop the Fairy chat application into a better system after this. The assignment has given me knowledge and understanding about the Java GUI application.

Das könnte Ihnen auch gefallen