Advertisement
KillianMills

ChatApplet.java

Nov 3rd, 2014
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1. /* Our chat client */
  2. import java.applet.*;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import java.io.*;
  6. import java.net.*;
  7.  
  8. class ChatClient extends Panel implements Runnable
  9. {
  10.     /* Display */
  11.     private TextField textfield = new TextField();
  12.     private TextArea textarea = new TextArea();
  13.     private Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
  14.  
  15.     /* Communication */
  16.     private Socket s;
  17.     private PrintWriter pw;
  18.     private BufferedReader br;
  19.  
  20.     public ChatClient(String host, int port, String nickname) {
  21.  
  22.     /* Set up display */
  23.     setLayout(new BorderLayout());
  24.         textarea.setFont(font);
  25.         textfield.setFont(font);
  26.     add(BorderLayout.SOUTH, textfield);
  27.     add(BorderLayout.CENTER, textarea);
  28.  
  29.     /* Associate sendChat with textfield callback */
  30.     textfield.addActionListener(new ActionListener() {
  31.         public void actionPerformed(ActionEvent e) {
  32.             sendChat(e.getActionCommand());
  33.         }
  34.         });
  35.  
  36.     try {
  37.         s = new Socket(host, port);
  38.         pw = new PrintWriter(s.getOutputStream(), true);
  39.         br = new BufferedReader(new InputStreamReader(s.getInputStream()));
  40.  
  41.         /* Send nickname to chat server */
  42.         pw.println(nickname);
  43.  
  44.         /* Become a thread */
  45.         new Thread(this).start();
  46.     } catch (IOException e) {System.out.println(e);}
  47.     }
  48.  
  49.     /* Called whenever user hits return in the textfield */
  50.     private void sendChat(String message) {
  51.         pw.println(message);
  52.         textfield.setText("");
  53.     }
  54.  
  55.     /* Add strings from chat server to the textarea */
  56.     public void run() {
  57.  
  58.     String message;
  59.  
  60.     try {
  61.         while (true) {
  62.         message = br.readLine();
  63.         textarea.append(message + "\n");
  64.         }
  65.     } catch (IOException e) {System.out.println(e);}
  66.     }
  67. }
  68.  
  69. public class ChatApplet extends Applet
  70. {
  71.     public void init() {
  72.  
  73.     /* Retrieve parameters */
  74.     int port = Integer.parseInt(getParameter("port"));
  75.     String host = getParameter("host");
  76.     String nickname = getParameter("nickname");
  77.  
  78.     /* Set up display */
  79.     setLayout(new BorderLayout());
  80.     add(BorderLayout.CENTER, new ChatClient(host, port, nickname));
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement