Advertisement
Guest User

Untitled

a guest
Jun 24th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.72 KB | None | 0 0
  1. /**
  2.  *  Java implementation of an Instant Messenger (IM) client
  3.  *  Designed for CS9035, on 2010-10-31
  4.  *
  5.  *  This Java program creates a window with two textboxes, one for storing the
  6.  *  log of messages, and one for a user to type a message into.
  7.  *
  8.  *  @version    1.0, 2010-10-31
  9.  *  @author     Me!
  10.  *  @since      1.6
  11.  *
  12. **/
  13. import java.awt.BorderLayout;
  14. import java.awt.Component;
  15. import java.awt.Dimension;
  16. import java.awt.EventQueue;
  17. import java.awt.event.ActionEvent;
  18. import java.awt.event.ActionListener;
  19.  
  20. import java.io.PrintWriter;
  21.  
  22. import java.net.ServerSocket;
  23. import java.net.Socket;
  24.  
  25. import javax.swing.Box;
  26. import javax.swing.BoxLayout;
  27. import javax.swing.JButton;
  28. import javax.swing.JFrame;
  29. import javax.swing.JLabel;
  30. import javax.swing.JPanel;
  31. import javax.swing.JScrollPane;
  32. import javax.swing.JTextArea;
  33. import javax.swing.ScrollPaneConstants;
  34.  
  35. import java.util.Scanner;
  36.  
  37. class InstantMessenger extends JFrame{
  38.  
  39.     // These variables are set separately, because they are needed for the inner class "buttonSendAction"
  40.     private JTextArea nextMessage;  // The JTextArea where a user types his message
  41.     private JTextArea messageLog;   // The JTextArea where a user can view the message log
  42.    
  43.     Socket connection;
  44.     Scanner fromClient;
  45.     PrintWriter toClient;
  46.    
  47.     public InstantMessenger() {
  48.         createWindow();
  49.     }
  50.    
  51.     public void createWindow(){
  52.    
  53.         // Properties of outermost window
  54.         // No need to call setSize(), pack() does this automatically.
  55.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  56.         setTitle("My Instant Messenger");
  57.         setLocation(200, 200);  // x, y
  58.        
  59.         // Lets put a JPanel in the JFrame, so we can do a little more.
  60.         JPanel mainPanel = new JPanel();
  61.         // Boxlayout - top to bottom
  62.         mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
  63.         add(mainPanel, BorderLayout.CENTER);
  64.        
  65.         // Create a title for the JTextArea that stores the message log.
  66.         JLabel messageLogTitle = new JLabel(" Message Log");
  67.         messageLogTitle.setAlignmentX(JLabel.CENTER_ALIGNMENT);
  68.        
  69.         // Create a text box for storing the message log
  70.         messageLog = new JTextArea();
  71.         messageLog.setEditable(false);
  72.         messageLog.setLineWrap(true);
  73.        
  74.         // Create a title for the next message JTextArea
  75.         JLabel messageTitle = new JLabel(" Message");
  76.         messageTitle.setAlignmentX(JLabel.CENTER_ALIGNMENT);
  77.        
  78.         // Create a text box for storing the next message
  79.         nextMessage = new JTextArea();    
  80.         nextMessage.setLineWrap(true);
  81.        
  82.         // Create a button
  83.         JButton buttonSend = new JButton("Send");
  84.         buttonSend.setAlignmentX(Component.CENTER_ALIGNMENT);
  85.         buttonSend.addActionListener(new ActionListener(){
  86.             public void actionPerformed(ActionEvent e) {
  87.                 // send message to other machine here.
  88.                 try{
  89.                     toClient = new PrintWriter(connection.getOutputStream(), true); // autoflush
  90.                     toClient.println(nextMessage.getText());
  91.                     if (nextMessage.getText().equals("QUIT")){
  92.                         messageLog.append("You have disconnected from the chat.\n");
  93.                         toClient.close();
  94.                         //fromClient.close(); // input Scanner - doesn't seem to be any different if it's commented out.
  95.                         connection.close();
  96.                     }
  97.                     else{
  98.                         messageLog.append("me: " + nextMessage.getText() + "\n");
  99.                     }
  100.                     nextMessage.setText("");
  101.                 } catch (Exception E){
  102.                     messageLog.append("Error sending previous message. Are you sure a client is connected?" + "\n");
  103.                 }
  104.             }
  105.         });
  106.        
  107.         // Make the two text fields scrollable
  108.         JScrollPane logScroller = new JScrollPane(messageLog);
  109.         logScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
  110.         logScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
  111.         logScroller.setPreferredSize(new Dimension(300,200));
  112.  
  113.         JScrollPane messageScroller = new JScrollPane(nextMessage);
  114.         messageScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
  115.         messageScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
  116.         messageScroller.setPreferredSize(new Dimension(300,50));
  117.        
  118.         // Add the components to the JPanel
  119.         mainPanel.add(messageLogTitle);
  120.         mainPanel.add(Box.createRigidArea(new Dimension(0,5)));    // 5 vertical pixels as a 'filler' space
  121.         mainPanel.add(logScroller);
  122.         mainPanel.add(Box.createRigidArea(new Dimension(0,5)));    // 5 vertical pixels as a 'filler' space
  123.         mainPanel.add(messageTitle);
  124.         mainPanel.add(Box.createRigidArea(new Dimension(0,5)));    // 5 vertical pixels as a 'filler' space
  125.         mainPanel.add(messageScroller);
  126.         mainPanel.add(buttonSend, Component.CENTER_ALIGNMENT);
  127.        
  128.         // Time to organize a little...
  129.         pack();
  130.     }
  131.        
  132.     public void startConnection(String mode, String host, int port){
  133.         try{
  134.             if (mode.equals("server")){
  135.                 ServerSocket s = new ServerSocket(port);
  136.                 messageLog.append("Waiting on port "+ port + " for a connection" + "\n");
  137.                 connection = s.accept();
  138.                 messageLog.append("Connected on port "+ port + "\n");
  139.             }
  140.             else if (mode.equals("client")){
  141.                 messageLog.append("Attempting to connect to "+ host + ":" + port + "\n");
  142.                 connection = new Socket(host, port);
  143.                 messageLog.append("Connected to "+ host + ":" + port + "\n");
  144.             }
  145.            
  146.             listen: while (connection.isConnected()) {  // when the client disconnects, this will crash, and go to the catch
  147.                 fromClient = new Scanner(connection.getInputStream());
  148.                 while(fromClient.hasNextLine()){
  149.                     String incomingMessage = fromClient.nextLine();
  150.                     if (incomingMessage.equals("QUIT")){
  151.                         messageLog.append("This chat has been terminated.\n");
  152.                         fromClient.close();
  153.                         connection.close();
  154.                         break listen;
  155.                     }
  156.                     else{
  157.                         messageLog.append("him: " + incomingMessage + "\n");
  158.                     }
  159.                 }
  160.             }
  161.         }
  162.         catch (java.net.UnknownHostException E){
  163.             System.out.println("Error connecting to server"); // typo on the hostname
  164.         }
  165.         catch (java.io.IOException E){
  166.             messageLog.append("Connection error, try again later.\n");
  167.             // You've been disconnected. Normal and expected. Either that, or you tried connecting to a non-existent server
  168.         }
  169.        
  170.     }
  171. }
  172.  
  173.  
  174. class testIM{
  175.     public static void main(String[] args) {
  176.  
  177.         String mode = "server";
  178.         String host = "127.0.0.1";
  179.         int port = 12345;
  180.        
  181.         if(args.length > 0)
  182.             mode = args[0];
  183.         if(args.length > 1)
  184.             host = args[1];
  185.        
  186.         final InstantMessenger IM = new InstantMessenger();
  187.         EventQueue.invokeLater(new Runnable() {
  188.             public void run() {
  189.                 IM.setVisible(true);
  190.             }
  191.         } );
  192.        
  193.         IM.startConnection(mode, host, port);          
  194.  
  195.     }
  196. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement