@Override public void run() { running = true; while (running) { try { if (connectedToRoom) { Server.sendLine(outRoom, ""); String msg = Server.readLine(inRoom, "Chatroom"); if (!msg.isEmpty()) { msgChat(msg); } } } catch (Exception e) { msgChat(e.getMessage()); try { // same as the standard disconnect from room inRoom.close(); outRoom.close(); roomSocket.close(); connectedToRoom = false; btnConnect.setText("Connect to room"); lRoomname.setText("Room: ---"); } catch (IOException e1) { e1.printStackTrace(); } } } }
public void connectToRoom() { int chatroom = roomList.getSelectedIndex(); String roomName = roomList.getSelectedValue(); try { Server.sendLine(outServer, "j"); Server.sendLine(outServer, chatroom + ""); String ans = Server.readLine(inServer, "Server/roomconnection"); roomPort = Integer.parseInt(ans); // error if not the port but "f" for failed, noob roomSocket = new Socket(serverC, roomPort); inRoom = new BufferedReader(new InputStreamReader(roomSocket.getInputStream())); outRoom = new PrintWriter(roomSocket.getOutputStream()); Server.sendLine(outRoom, tfUsername.getText()); connectedToRoom = true; btnConnect.setText("Leave room"); lRoomname.setText("Room: " + roomName); } catch (Exception e) { msgChat(e.getMessage()); try { // same as the standard disconnect from server inServer.close(); outServer.close(); serverSocket.close(); connectedToServer = false; btnConnectServer.setText("Connect to server"); enableButtons(false); } catch (IOException e1) { e1.printStackTrace(); } } }
public void connectToServer() { // TODO get port? String ip = ""; while (ip.isEmpty()) { ip = JOptionPane.showInputDialog("Server address:", "localhost"); if (ip == null) { return; } } if (ip != null) { serverC = ip; serverPort = 10000; roomList.removeAll(); try { serverSocket = new Socket(serverC, serverPort); inServer = new BufferedReader(new InputStreamReader(serverSocket.getInputStream())); outServer = new PrintWriter(serverSocket.getOutputStream()); getList(); connectedToServer = true; btnConnectServer.setText("Disconnect from server"); enableButtons(true); } catch (Exception e) { msgChat(e.getMessage()); } } }