[Java] java打字练习软件 →→→→→进入此内容的聊天室

来自 , 2019-09-13, 写在 Java, 查看 111 次.
URL http://www.code666.cn/view/35464c84
  1. package at.ac.uni_linz.tk.vchat;
  2.  
  3. import java.io.*;
  4. import java.net.*;
  5. import java.awt.*;
  6. import java.awt.image.*;
  7.  
  8. /**
  9.  * Implements the methods for the client side's networking. Opens a socket
  10.  * connection and Input- and OutputStreams to the ChatServer, sends and receives
  11.  * data. It also includes the functionality for User logins and logouts.
  12.  *
  13.  * @author Arno Huetter (C)opyright by the Institute for Computer Science,
  14.  *         Telecooperation Department, University of Linz
  15.  */
  16.  
  17. public class ChatClient implements Runnable {
  18.  
  19.     private Socket clientSocket;
  20.     private Thread clientThread;
  21.     private String host;
  22.     private boolean connected;
  23.     private ChatApplet chatApplet;
  24.  
  25.     private ObjectOutputStream output;
  26.     private ObjectInputStream input;
  27.  
  28.     private UserLoginRequest userLogin;
  29.  
  30.     /**
  31.      * Constructs the ChatClient.
  32.      *
  33.      * @param hostParam
  34.      *            the host where the ChatApplet descends from (that is also
  35.      *            where the ChatServer ought to be running)
  36.      * @param portParam
  37.      *            the standard port where the ChatServer is listening
  38.      * @param chatParam
  39.      *            the ChatApplet which administrates the users
  40.      */
  41.  
  42.     public ChatClient(String hostParam, ChatApplet chatParam) {
  43.         host = hostParam;
  44.         chatApplet = chatParam;
  45.     }
  46.  
  47.     /**
  48.      * Connects to the ChatServer.
  49.      *
  50.      * @param portParam
  51.      *            the port where the ChatServer is listening
  52.      */
  53.  
  54.     public void connect(int portParam) {
  55.         try {
  56.             chatApplet.setStatus("Connecting...", true);
  57.             clientSocket = new Socket(host, portParam);
  58.  
  59.             /*
  60.              * Open Input- and OutputStreams
  61.              */
  62.             input = new ObjectInputStream(clientSocket.getInputStream());
  63.             output = new ObjectOutputStream(clientSocket.getOutputStream());
  64.  
  65.             try {
  66.                 Thread.sleep(1000);
  67.             } catch (InterruptedException excpt) {
  68.             }
  69.  
  70.             /*
  71.              * Start the thread that is receiving data
  72.              */
  73.             clientThread = new Thread(this);
  74.             clientThread.start();
  75.             connected = true;
  76.             chatApplet.setStatus("Connected", true);
  77.         } catch (Exception excpt) {
  78.             connected = false;
  79.             System.out.println("Exception while connecting: " + excpt);
  80.             chatApplet
  81.                     .setStatus(
  82.                             "Exception while connecting. Server down, firewall config or file-URL applet.",
  83.                             true);
  84.         }
  85.     }
  86.  
  87.     /**
  88.      * Waits for the ChatServer's reply to a login request.
  89.      */
  90.  
  91.     public void waitForLoginReply() {
  92.         while (userLogin.status == UserLoginRequest.REQUESTED && connected()) {
  93.             try {
  94.                 Thread.sleep(100);
  95.             } catch (InterruptedException excpt) {
  96.             }
  97.         }
  98.     }
  99.  
  100.     /**
  101.      * Connects to the ChatServer and sends a login request for an existing
  102.      * User.
  103.      *
  104.      * @param userNameParam
  105.      *            the name of the User to login
  106.      * @param userPasswordParam
  107.      *            the password of the User to login
  108.      * @param portParam
  109.      *            the port where the ChatServer is listening
  110.      */
  111.  
  112.     public void connectAsExistingUser(String userNameParam,
  113.             String userPasswordParam, int portParam) {
  114.         int lastUserId;
  115.  
  116.         connect(portParam);
  117.         if (connected) {
  118.             chatApplet.setStatus("Connecting as existing user...", true);
  119.             chatApplet.stopSimulator();
  120.             chatApplet.removeAllExceptDefaultRoom();
  121.             userLogin = new ExistingUserLoginRequest(userNameParam,
  122.                     userPasswordParam);
  123.             send(userLogin);
  124.             chatApplet.setStatus("Waiting for server reply...", true);
  125.             waitForLoginReply();
  126.             if (userLogin.status == UserLoginRequest.ACCEPTED) {
  127.                 lastUserId = chatApplet.getCurrentUserId();
  128.                 chatApplet.setCurrentUser(userLogin.user);
  129.  
  130.                 if (userLogin.user.getId() != lastUserId)
  131.                     chatApplet.removeUser(lastUserId);
  132.  
  133.                 chatApplet.restartHistory();
  134.                 chatApplet.setStatus("Login accepted: "
  135.                         + userLogin.statusString, true);
  136.                 chatApplet.setFrameVisibility(true);
  137.             } else {
  138.                 disconnect();
  139.                 chatApplet.setStatus("Login denied: " + userLogin.statusString,
  140.                         true);
  141.             }
  142.         }
  143.     }
  144.  
  145.     /**
  146.      * Connects to the ChatServer and sends a login request for a new User.
  147.      *
  148.      * @param userParam
  149.      *            the User to login
  150.      * @param portParam
  151.      *            the port where the ChatServer is listening
  152.      */
  153.  
  154.     public void connectAsNewUser(User userParam, int portParam) {
  155.         int lastUserId;
  156.  
  157.         connect(portParam);
  158.         if (connected) {
  159.             chatApplet.setStatus("Connecting as new user...", true);
  160.             chatApplet.stopSimulator();
  161.             chatApplet.removeAllExceptDefaultRoom();
  162.  
  163.             userLogin = new NewUserLoginRequest(userParam);
  164.             send(userLogin);
  165.             chatApplet.setStatus("Waiting for server reply...", true);
  166.             waitForLoginReply();
  167.             if (userLogin.status == UserLoginRequest.ACCEPTED) {
  168.                 lastUserId = chatApplet.getCurrentUserId();
  169.                 chatApplet.setCurrentUser(userLogin.user);
  170.  
  171.                 if (userLogin.user.getId() != lastUserId)
  172.                     chatApplet.removeUser(lastUserId);
  173.  
  174.                 chatApplet.restartHistory();
  175.                 chatApplet.setStatus("Login accepted: "
  176.                         + userLogin.statusString, true);
  177.                 chatApplet.setFrameVisibility(true);
  178.             } else {
  179.                 disconnect();
  180.                 chatApplet.setStatus("Login denied: " + userLogin.statusString,
  181.                         true);
  182.             }
  183.         }
  184.     }
  185.  
  186.     /**
  187.      * Disconnects from the ChatServer.
  188.      */
  189.  
  190.     public void disconnect() {
  191.         try {
  192.             send(new UserLogoutEvent(chatApplet.getCurrentUserId()));
  193.             if (clientThread != null && clientThread.isAlive())
  194.                 clientThread.stop();
  195.             if (output != null)
  196.                 output.close();
  197.             if (input != null)
  198.                 input.close();
  199.             if (clientSocket != null)
  200.                 clientSocket.close();
  201.             chatApplet.setStatus("Disconnected", true);
  202.         } catch (IOException excpt) {
  203.             System.out.println("Exception while disconnecting: " + excpt);
  204.             chatApplet.setStatus("Exception while disconnecting", true);
  205.         } finally {
  206.             connected = false;
  207.             chatApplet.removeAllExceptCurrentUser();
  208.             chatApplet.removeAllExceptDefaultRoom();
  209.         }
  210.     }
  211.  
  212.     /**
  213.      * Runs a thread that is receiving data from the InpuStream openend to the
  214.      * ChatServer.
  215.      */
  216.  
  217.     public void run() {
  218.         Object receivedObject;
  219.         User user;
  220.         while (connected) {
  221.             try {
  222.                 receivedObject = input.readObject();
  223.                 chatApplet.setStatus("Receiving data");
  224.                 if (receivedObject instanceof UserPositionEvent)
  225.                     chatApplet.setUserPosition(
  226.                             ((UserPositionEvent) receivedObject).userId,
  227.                             ((UserPositionEvent) receivedObject).userPosition,
  228.                             false);
  229.                 else if (receivedObject instanceof UserHeadingEvent)
  230.                     chatApplet.setUserHeading(
  231.                             ((UserHeadingEvent) receivedObject).userId,
  232.                             ((UserHeadingEvent) receivedObject).userHeading,
  233.                             false);
  234.                 else if (receivedObject instanceof UserMessageEvent)
  235.                     chatApplet.setUserMessage(
  236.                             ((UserMessageEvent) receivedObject).userId,
  237.                             ((UserMessageEvent) receivedObject).userMessage,
  238.                             false);
  239.                 else if (receivedObject instanceof UserMoodEvent)
  240.                     chatApplet.setUserMood(
  241.                             ((UserMoodEvent) receivedObject).userId,
  242.                             ((UserMoodEvent) receivedObject).userMood, false);
  243.                 else if (receivedObject instanceof UserRoomEvent) {
  244.                     chatApplet.moveUserToRoom(
  245.                             ((UserRoomEvent) receivedObject).userId,
  246.                             ((UserRoomEvent) receivedObject).roomId, false);
  247.                     chatApplet.setUserPosition(
  248.                             ((UserRoomEvent) receivedObject).userId,
  249.                             ((UserRoomEvent) receivedObject).position, false);
  250.                 } else if (receivedObject instanceof UserUpdateEvent) {
  251.                     chatApplet.updateUser(
  252.                             ((UserUpdateEvent) receivedObject).user, false);
  253.                     if (((UserUpdateEvent) receivedObject).user.getId() == chatApplet
  254.                             .getCurrentUserId()) {
  255.                         chatApplet
  256.                                 .setStatus(
  257.                                         ((UserUpdateEvent) receivedObject).statusString,
  258.                                         false);
  259.                     }
  260.                 } else if (receivedObject instanceof UserLoginEvent)
  261.                     chatApplet.addUser(((UserLoginEvent) receivedObject).user);
  262.                 else if (receivedObject instanceof UserLogoutEvent) {
  263.                     chatApplet
  264.                             .removeUser(((UserLogoutEvent) receivedObject).userId);
  265.                 } else if (receivedObject instanceof NewUserLoginRequest) {
  266.                     chatApplet.setStatus("Received login", true);
  267.                     userLogin = (NewUserLoginRequest) receivedObject;
  268.                 } else if (receivedObject instanceof ExistingUserLoginRequest) {
  269.                     chatApplet.setStatus("Received login", true);
  270.                     userLogin = (ExistingUserLoginRequest) receivedObject;
  271.                 } else if (receivedObject instanceof RoomUpdateEvent) {
  272.                     chatApplet.setStatus("Received room update", true);
  273.                     chatApplet.updateRoom(
  274.                             ((RoomUpdateEvent) receivedObject).room, false);
  275.                 } else if (receivedObject instanceof RoomCreateEvent) {
  276.                     chatApplet.setStatus("Received room creation", true);
  277.                     chatApplet.updateRoom(
  278.                             ((RoomCreateEvent) receivedObject).room, false);
  279.                 } else if (receivedObject instanceof RoomListEvent) {
  280.                     chatApplet.setStatus("Received room list", true);
  281.                     chatApplet
  282.                             .setRoomTable(((RoomListEvent) receivedObject).roomTable);
  283.                 } else if (receivedObject instanceof RoomRemoveEvent) {
  284.                     chatApplet.setStatus("Received room removal", true);
  285.                     chatApplet.forceRoomRemoval(
  286.                             ((RoomRemoveEvent) receivedObject).roomId, false);
  287.                 }
  288.             } catch (Exception excpt) {
  289.                 System.out.println("Exception while receiving data: " + excpt
  290.                         + ". Going offline...");
  291.                 chatApplet.setStatus(
  292.                         "Exception while receiving data. Going offline...",
  293.                         true);
  294.                 disconnect();
  295.             }
  296.         }
  297.     }
  298.  
  299.     /**
  300.      * Sends data over the OutputStream openend to the ChatServer.
  301.      *
  302.      * @param sendObject
  303.      *            the object to be sent
  304.      */
  305.  
  306.     public void send(Object sendObject) {
  307.         try {
  308.             if (connected) {
  309.                 chatApplet.setStatus("Sending data");
  310.                 output.writeObject(sendObject);
  311.             }
  312.         } catch (IOException excpt) {
  313.             System.out.println("Exception while sending data: " + excpt
  314.                     + ". Going offline...");
  315.             chatApplet.setStatus(
  316.                     "Exception while sending data. Going offline...", true);
  317.             disconnect();
  318.         }
  319.     }
  320.  
  321.     /**
  322.      * Sends data over the OutputStream openend to the ChatServer.
  323.      *
  324.      * @param sendObject
  325.      *            the object to be sent
  326.      */
  327.  
  328.     public boolean connected() {
  329.         return connected;
  330.     }
  331.  
  332.     /**
  333.      * Returns the host where the ChatClient is opening connections to.
  334.      */
  335.  
  336.     public String getHost() {
  337.         return host;
  338.     }
  339.  
  340. }
  341.  

回复 "java打字练习软件"

这儿你可以回复上面这条便签

captcha