This Java Code supports two-way chatting between users. It implements a client for the ConnectionBroker server, which can set up a relayed connection between a pair of such clients. There are really two functions: The user can register with the server as a client who is willing to accept a connection, or the user can make a connection with one of the clients who is waiting on the server. The code retrieves and displays a list of waiting clients when it starts. There is a Refresh button that the user can click to refresh this list (since the list of waiting clients can change from time to time).
The user connects with one of the clients on the list by clicking it and then clicking a Connect button. Finally, there is a register button that will add the user to the list and then wait for a connection. There is an input box where the user can enter a name or other information to be displayed in other users’ client lists. The use can be a party to multiple connections simultaneously. A separator window opens for each connection that can be used to send and retrieve messages.
A parameter named “server” can be used to specify the name or IP number of the server computer. If none is specified, the computer from which the application was loaded is used. Another application parameter, named “port”, can be used to specify the port on which the server is listening. If none is specified, then the port given by the constant DEFAULT_PORT is used. This class can also be run as a standalone application. In that case, the server must be specified as the first command-line parameter. The port, if different from the DEFAULT_PORT, can be specified as the second parameter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.ArrayList; import javax.swing.*; public class BrokeredChat implements ActionListener { public static void main(String[] args) { if (args.length == 0) { System.out.println("Usage: java BrokeredChat <server> [<port>]"); return; } SwingUtilities.invokeLater(() -> { new BrokeredChat(args[0], args.length > 1 ? Integer.parseInt(args[1]) : DEFAULT_PORT); }); } static final char REGISTER = '['; static final char CONNECT = '='; static final char SEND_CLIENT_LIST = ':'; static final char NOT_AVAILABLE = '!'; static final char CONNECTED = '.'; static final char CLIENT_INFO = '>'; static final char END_CLIENT_INFO = '<'; static final int DEFAULT_PORT = 3030; private JFrame window; private JLabel display; private JComboBox<String> clients; private JButton connectButton; private JButton refreshButton; private JButton registerButton; private JTextField infoInput; private ArrayList<String> clientStrings; private String computer; private int port; public BrokeredChat(String computer, int port) { this.computer = computer; this.port = port; window = new JFrame("BrokeredChat"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setContentPane(makeInterfacePanel()); window.setPreferredSize(new Dimension(500, 135)); window.pack(); window.setLocation(20, 50); window.setVisible(true); doCommand(SEND_CLIENT_LIST); } private JPanel makeInterfacePanel() { JPanel panel = new JPanel(); panel.setBackground(Color.lightGray); panel.setLayout(new GridLayout(4, 1, 5, 5)); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); JPanel top = new JPanel(); top.setBackground(Color.lightGray); top.setLayout(new BorderLayout(2, 2)); JPanel middle = new JPanel(); middle.setBackground(Color.lightGray); middle.setLayout(new BorderLayout(5, 5)); JPanel bottom = new JPanel(); bottom.setBackground(Color.lightGray); bottom.setLayout(new GridLayout(1, 2, 5, 5)); display = new JLabel("", JLabel.CENTER); display.setForeground(new Color(200, 0, 0)); panel.add(top); panel.add(display); panel.add(middle); panel.add(bottom); clients = new JComboBox<>(); clients.setBackground(Color.white); connectButton = new JButton("Connect to Selected User"); connectButton.addActionListener(this); refreshButton = new JButton("Refresh User List"); refreshButton.addActionListener(this); registerButton = new JButton("Register"); registerButton.addActionListener(this); infoInput = new JTextField(); infoInput.setBackground(Color.white); infoInput.addActionListener(this); top.add(infoInput, BorderLayout.CENTER); top.add(registerButton, BorderLayout.EAST); top.add(new JLabel("Register with Server as: "), BorderLayout.WEST); middle.add(clients, BorderLayout.CENTER); middle.add(new JLabel("List of Available Users: "), BorderLayout.WEST); bottom.add(refreshButton); bottom.add(connectButton); return panel; } public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source == connectButton) { doCommand(CONNECT); } else if (source == registerButton || source == infoInput) { doCommand(REGISTER); } else { doCommand(SEND_CLIENT_LIST); } } void doCommand(char command) { // Create a thread to contact the server to carry out // the command, which can be one of CONNECT, REGISTER, // or SEND_CLIENT_LIST. String message; // Command to be sent to server. String name; // Name for connection window. if (command == CONNECT) { // Connect to the user select in the client list. // The command to the server must contain the ID // number of the client. This is in the clientStrings // list. The String in this list consists of the // client ID followed optionally by a space and the // description under which that client registered. int partner = clients.getSelectedIndex(); if (clientStrings == null || partner < 0 || partner >= clientStrings.size()) { // This really shouldn't be possible. display.setText("Can't connect -- no user!"); return; } String info = (String)clientStrings.get(partner); int pos = info.indexOf(" "); if (pos > 0) { message = "" + CONNECT + info.substring(0,pos); name = info.substring(pos+1); } else { message = "" + CONNECT + info; name = "unknown user"; } } else if (command == REGISTER) { // Register with the server. The string from the // infoInput is sent to the server as the description // of the client and will appear in a client list // that is downloaded from the server. name = infoInput.getText().trim(); if (name.length() == 0) { display.setText("To register, you must enter a name."); return; } infoInput.setText(""); message = REGISTER + name; display.setText("Contacting server to register you..."); } else { // The command is to get the client list from the server. clients.removeAllItems(); clients.addItem("(Checking)"); message = "" + SEND_CLIENT_LIST; display.setText("Contacting server to get user list..."); name = null; } registerButton.setEnabled(false); // Buttons are disabled until operation completes. connectButton.setEnabled(false); refreshButton.setEnabled(false); new ConnectionHandler(message,name); // Create thread to do the command. } class ConnectionHandler extends Thread { // A thread to handle a connection to the server. String message; // Message to be sent to the server. // First character tells which of the three // possible types of message this is. String name; // Name to appear in the title bar of the ChatWindow. // Used only for CONNECT and REGISTER commands. ConnectionHandler(String message, String name) { this.message = message; this.name = name; start(); // Thread starts as soon as it is created. } public void run() { Socket connection = null; ArrayList clients = null; // Will be the list of clients from the server. String displayText = "Client list has been received."; // This will be changed if an error occurs or if the // CONNECT or REGISTER commands complete. try { if (message.charAt(0) == REGISTER) { // Register with the server and open a server window // to wait for a connection request to come in from // another user. connection = new Socket(computer,port); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.println(message); out.flush(); if (out.checkError()) throw new IOException("Can't send command."); new ChatWindow("Outgoing Connection (" + name + ")", connection,true); displayText = "Opening window to wait for connection"; } else if (message.charAt(0) == CONNECT) { // Try to connect to another user, and open a window // for chatting with that user. connection = new Socket(computer,port); connection.setSoTimeout(30000); // only wait 30 seconds TextReader in = new TextReader(connection.getInputStream()); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.println(message); // Request the connection. out.flush(); if (out.checkError()) throw new IOException("Can't send command."); String answer = in.getln(); // Read the server's response. if (answer.length() == 0 || answer.charAt(0) != CONNECTED) { displayText = "Can't connect to " + name; } else { connection.setSoTimeout(0); // Turn off timeout new ChatWindow("Connection to " + name, connection); displayText = "Opening connection to " + name; } } // Get client list. This is done after a CONNECT or // REGISTER, as well as for a SEND_CLIENT_LIST. connection = null; connection = new Socket(computer,port); connection.setSoTimeout(30000); // Only wait 30 seconds for response. TextReader in = new TextReader(connection.getInputStream()); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.println("" + SEND_CLIENT_LIST); // Request the client list. out.flush(); if (out.checkError()) throw new IOException("Can't send command."); ArrayList clientInfo = new ArrayList(); while (true) { // Get the responses and put them in the clientInfo list. String line = in.getln(); if (line.length() > 0) { if (line.charAt(0) == END_CLIENT_INFO) break; else if (line.charAt(0) == CLIENT_INFO) clientInfo.add( line.substring(1) ); else throw new IOException("Bad data received."); } } clients = clientInfo; } catch (Exception e) { displayText = "Error: " + e.getMessage(); } finally{ finishConnection(clients,displayText); if (connection != null) { try { connection.close(); } catch (IOException e) { } } } } } void finishConnection(final ArrayList clientList, final String displayText) { // This is called by the thread that carries out a command, after // the command has completed or has caused an error. If an // error occurred, then clientList is null. Otherwise it is // the list of clients, possibly empty, that has been retrieved // from the server. The second parameter is the text to // be displayed on the display JLabel. SwingUtilities.invokeLater ( new Runnable() { public void run() { if (clientList == null) { clients.removeAllItems(); clients.addItem("(Can't connect)"); } else if (clientList.size() == 0) { clients.removeAllItems(); clients.addItem("(None available)"); } else { // Show list of clients and turn on connect button // so user can open a connection to one of them. makeClientList(clientList); connectButton.setEnabled(true); } display.setText(displayText); refreshButton.setEnabled(true); // Re-enable buttons. registerButton.setEnabled(true); clientStrings = clientList; } } ); } void makeClientList(ArrayList clientInfo) { // Change the JComboBox to show the clients in the list. clientStrings = clientInfo; clients.removeAllItems(); for (int i = 0; i < clientInfo.size(); i++) { // The strings in clientInfo consist of an ID number // followed optionally by a user name. If there is // no user name, then the ID number is shown in the list. String info = (String)clientInfo.get(i); int spacePos = info.indexOf(" "); if (spacePos > 0) info = info.substring(spacePos+1); clients.addItem(info); } } } // end class BrokeredChat |