Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Java implementation of an Instant Messenger (IM) client
- * Designed for CS9035, on 2010-10-31
- *
- * This Java program creates a window with two textboxes, one for storing the
- * log of messages, and one for a user to type a message into.
- *
- * @version 1.0, 2010-10-31
- * @author Me!
- * @since 1.6
- *
- **/
- import java.awt.BorderLayout;
- import java.awt.Component;
- import java.awt.Dimension;
- import java.awt.EventQueue;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- import javax.swing.Box;
- import javax.swing.BoxLayout;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- import javax.swing.JScrollPane;
- import javax.swing.JTextArea;
- import javax.swing.ScrollPaneConstants;
- import java.util.Scanner;
- class InstantMessenger extends JFrame{
- // These variables are set separately, because they are needed for the inner class "buttonSendAction"
- private JTextArea nextMessage; // The JTextArea where a user types his message
- private JTextArea messageLog; // The JTextArea where a user can view the message log
- Socket connection;
- Scanner fromClient;
- PrintWriter toClient;
- public InstantMessenger() {
- createWindow();
- }
- public void createWindow(){
- // Properties of outermost window
- // No need to call setSize(), pack() does this automatically.
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setTitle("My Instant Messenger");
- setLocation(200, 200); // x, y
- // Lets put a JPanel in the JFrame, so we can do a little more.
- JPanel mainPanel = new JPanel();
- // Boxlayout - top to bottom
- mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
- add(mainPanel, BorderLayout.CENTER);
- // Create a title for the JTextArea that stores the message log.
- JLabel messageLogTitle = new JLabel(" Message Log");
- messageLogTitle.setAlignmentX(JLabel.CENTER_ALIGNMENT);
- // Create a text box for storing the message log
- messageLog = new JTextArea();
- messageLog.setEditable(false);
- messageLog.setLineWrap(true);
- // Create a title for the next message JTextArea
- JLabel messageTitle = new JLabel(" Message");
- messageTitle.setAlignmentX(JLabel.CENTER_ALIGNMENT);
- // Create a text box for storing the next message
- nextMessage = new JTextArea();
- nextMessage.setLineWrap(true);
- // Create a button
- JButton buttonSend = new JButton("Send");
- buttonSend.setAlignmentX(Component.CENTER_ALIGNMENT);
- buttonSend.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e) {
- // send message to other machine here.
- try{
- toClient = new PrintWriter(connection.getOutputStream(), true); // autoflush
- toClient.println(nextMessage.getText());
- if (nextMessage.getText().equals("QUIT")){
- messageLog.append("You have disconnected from the chat.\n");
- toClient.close();
- //fromClient.close(); // input Scanner - doesn't seem to be any different if it's commented out.
- connection.close();
- }
- else{
- messageLog.append("me: " + nextMessage.getText() + "\n");
- }
- nextMessage.setText("");
- } catch (Exception E){
- messageLog.append("Error sending previous message. Are you sure a client is connected?" + "\n");
- }
- }
- });
- // Make the two text fields scrollable
- JScrollPane logScroller = new JScrollPane(messageLog);
- logScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
- logScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
- logScroller.setPreferredSize(new Dimension(300,200));
- JScrollPane messageScroller = new JScrollPane(nextMessage);
- messageScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
- messageScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
- messageScroller.setPreferredSize(new Dimension(300,50));
- // Add the components to the JPanel
- mainPanel.add(messageLogTitle);
- mainPanel.add(Box.createRigidArea(new Dimension(0,5))); // 5 vertical pixels as a 'filler' space
- mainPanel.add(logScroller);
- mainPanel.add(Box.createRigidArea(new Dimension(0,5))); // 5 vertical pixels as a 'filler' space
- mainPanel.add(messageTitle);
- mainPanel.add(Box.createRigidArea(new Dimension(0,5))); // 5 vertical pixels as a 'filler' space
- mainPanel.add(messageScroller);
- mainPanel.add(buttonSend, Component.CENTER_ALIGNMENT);
- // Time to organize a little...
- pack();
- }
- public void startConnection(String mode, String host, int port){
- try{
- if (mode.equals("server")){
- ServerSocket s = new ServerSocket(port);
- messageLog.append("Waiting on port "+ port + " for a connection" + "\n");
- connection = s.accept();
- messageLog.append("Connected on port "+ port + "\n");
- }
- else if (mode.equals("client")){
- messageLog.append("Attempting to connect to "+ host + ":" + port + "\n");
- connection = new Socket(host, port);
- messageLog.append("Connected to "+ host + ":" + port + "\n");
- }
- listen: while (connection.isConnected()) { // when the client disconnects, this will crash, and go to the catch
- fromClient = new Scanner(connection.getInputStream());
- while(fromClient.hasNextLine()){
- String incomingMessage = fromClient.nextLine();
- if (incomingMessage.equals("QUIT")){
- messageLog.append("This chat has been terminated.\n");
- fromClient.close();
- connection.close();
- break listen;
- }
- else{
- messageLog.append("him: " + incomingMessage + "\n");
- }
- }
- }
- }
- catch (java.net.UnknownHostException E){
- System.out.println("Error connecting to server"); // typo on the hostname
- }
- catch (java.io.IOException E){
- messageLog.append("Connection error, try again later.\n");
- // You've been disconnected. Normal and expected. Either that, or you tried connecting to a non-existent server
- }
- }
- }
- class testIM{
- public static void main(String[] args) {
- String mode = "server";
- String host = "127.0.0.1";
- int port = 12345;
- if(args.length > 0)
- mode = args[0];
- if(args.length > 1)
- host = args[1];
- final InstantMessenger IM = new InstantMessenger();
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- IM.setVisible(true);
- }
- } );
- IM.startConnection(mode, host, port);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement