// サーバーから送られてきたメッセージの処理 public void reachedMessage(String name, String value) { // チャットルームのリストに変更が加えられた if (name.equals("rooms")) { if (value.equals("")) { roomList.setModel(new DefaultListModel()); } else { String[] rooms = value.split(" "); roomList.setListData(rooms); } } // ユーザーが入退室した else if (name.equals("users")) { if (value.equals("")) { userList.setModel(new DefaultListModel()); } else { String[] users = value.split(" "); userList.setListData(users); } } // メッセージが送られてきた else if (name.equals("msg")) { msgTextArea.append(value + "\n"); } // 処理に成功した else if (name.equals("successful")) { if (value.equals("setName")) msgTextArea.append(">名前を変更しました\n"); } // エラーが発生した else if (name.equals("error")) { msgTextArea.append("ERROR>" + value + "\n"); } }
// サーバーに接続する public void connectServer() { try { socket = new Socket(HOST, PORT); msgTextArea.append(">サーバーに接続しました\n"); } catch (Exception err) { msgTextArea.append("ERROR>" + err + "\n"); } }
// Utility methods // Send message to client private void sendMessage(String message) { try { output.writeObject("KELVIN: " + message); output.flush(); showMessage("\nKELVIN: " + message); } catch (IOException ioException) { chatWindow.append("\n ERROR: CANNOT SEND MESSAGE! \n"); } }
public ConnectFourServer() { JTextArea jtaLog = new JTextArea(); // Create a scroll pane to hold text area JScrollPane scrollPane = new JScrollPane(jtaLog); // Add the scroll pane to the frame add(scrollPane, BorderLayout.CENTER); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 300); setTitle("TicTacToeServer"); setVisible(true); try { // Create a server socket ServerSocket serverSocket = new ServerSocket(8000); jtaLog.append(new Date() + ": Server started at socket 8000\n"); // Number a session int sessionNo = 1; // Ready to create a session for every two players while (true) { jtaLog.append(new Date() + ": Wait for players to join session " + sessionNo + '\n'); // Connect to player 1 Socket player1 = serverSocket.accept(); jtaLog.append(new Date() + ": Player 1 joined session " + sessionNo + '\n'); jtaLog.append("Player 1's IP address" + player1.getInetAddress().getHostAddress() + '\n'); // Notify that the player is Player 1 new DataOutputStream(player1.getOutputStream()).writeInt(PLAYER1); // Connect to player 2 Socket player2 = serverSocket.accept(); jtaLog.append(new Date() + ": Player 2 joined session " + sessionNo + '\n'); jtaLog.append("Player 2's IP address" + player2.getInetAddress().getHostAddress() + '\n'); // Notify that the player is Player 2 new DataOutputStream(player2.getOutputStream()).writeInt(PLAYER2); // Display this session and increment session number jtaLog.append(new Date() + ": Start a thread for session " + sessionNo++ + '\n'); // Create a new thread for this session of two players HandleASession task = new HandleASession(player1, player2); // Start the new thread new Thread(task).start(); } } catch (IOException ex) { System.err.println(ex); } }
// メッセージをサーバーに送信する public void sendMessage(String msg) { try { OutputStream output = socket.getOutputStream(); PrintWriter writer = new PrintWriter(output); writer.println(msg); writer.flush(); } catch (Exception err) { msgTextArea.append("ERROR>" + err + "\n"); } }
public void run() { String texto = ""; while (repetir) { try { Empleados e = (Empleados) inObjeto.readObject(); textarea1.setText(""); textarea1.setForeground(Color.blue); if (e == null) { textarea1.setForeground(Color.red); PintaMensaje("<<EL EMPLEADO NO EXISTE>>"); } else { texto = "Empleado: " + e.getEmpNo() + "\n " + "Oficio: " + e.getOficio() + "\tApellido: " + e.getApellido() + "\n " + "Comisión: " + e.getComision() + "\tDirección: " + e.getDir() + "\n " + "Alta: " + e.getFechaAlt() + "\tSalario: " + e.getSalario() + "\n " + "Departamento: " + e.getDepartamentos().getDnombre(); textarea1.append(texto); } } catch (SocketException s) { repetir = false; } catch (IOException e) { e.printStackTrace(); repetir = false; } catch (ClassNotFoundException e) { e.printStackTrace(); repetir = false; } } try { socket.close(); System.exit(0); } catch (IOException e) { e.printStackTrace(); } }
@Override public void run() { // TODO Auto-generated method stub String inputLine; try { while ((inputLine = in.readLine()) != null) { inputLine = "\nYour peer says >> " + inputLine; chatField.append(inputLine); } out.close(); in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Override public void run() { // TODO Auto-generated method stub try { Socket s = new Socket(hostin, portin); InputStream ins = s.getInputStream(); OutputStream os = s.getOutputStream(); ir = new BufferedReader(new InputStreamReader(ins)); pw = new PrintWriter(new OutputStreamWriter(os), true); pw.print(nick); while (true) { String line = ir.readLine(); jta.append(line + "\n"); jsp.getVerticalScrollBar().setValue(jsp.getVerticalScrollBar().getMaximum()); } } catch (IOException e) { e.printStackTrace(); } }
public void actionPerformed(ActionEvent e) { if (e.getSource() == butConnect) { try { boolean ok = serverConnection(); if (ok) { setInitPanel(); } else { System.out.println("Le pseudo existe déjà, choisissez en un autre."); } } catch (IOException err) { System.err.println( "Problème de connection avec le serveur: " + err.getMessage() + "\n.Arrêt..."); System.exit(1); } } else if (e.getSource() == butListParty) { try { // envoyer requête LIST PARTY oos.writeInt(JungleServer.REQ_LISTPARTY); oos.flush(); // recevoir résultat et l'afficher dans textInfoInit System.out.println("flush"); boolean pret = ois.readBoolean(); System.out.println(pret); if (pret) { String nomParty = (String) ois.readObject(); System.out.println("apres read"); textInfoInit.append(nomParty + " "); } } catch (ClassNotFoundException err) { } catch (IOException err) { System.err.println( "Problème de connection avec le serveur: " + err.getMessage() + "\n.Arrêt..."); System.exit(1); } } else if (e.getSource() == butCreateParty) { try { boolean ok; // envoyer requête CREATE PARTY (paramètres : nom partie et nb joueurs nécessaires) oos.writeInt(JungleServer.REQ_CREATEPARTY); oos.writeObject(textCreate.getText()); int nbJoueurs = (Integer) spinNbPlayer.getValue(); oos.writeInt(nbJoueurs); oos.flush(); // recevoir résultat -> ok ok = ois.readBoolean(); System.out.println(ok); // si ok == true : if (ok) { // mettre le panneau party au centre setPartyPanel(); // afficher un message dans textInfoParty comme quoi il faut attendre le début de partie textInfoParty.append("Attendre le début de la partie"); // créer un ThreadClient et lancer son exécution ThreadClient threadClient = new ThreadClient(this); threadClient.start(); } } catch (IOException err) { System.err.println( "probleme de connection serveur : " + err.getMessage() + "\n.Aborting..."); System.exit(1); } } else if (e.getSource() == butJoinParty) { try { int idPlayer; // envoyer requête JOIN PARTY (paramètres : numero partie) oos.writeInt(JungleServer.REQ_JOINPARTY); oos.flush(); System.out.println("requete envoyée"); int numPartie = Integer.parseInt(textJoin.getText()); oos.writeInt(numPartie); oos.flush(); System.out.println("numPartie flushé"); // recevoir résultat -> idPlayer idPlayer = ois.readInt(); System.out.println("idplayer reçu : " + idPlayer); // si idPlayer >= 1 : if (idPlayer >= 1) { // mettre le panneau party au centre setPartyPanel(); // afficher un message dans textInfoParty comme quoi il faut attendre le début de partie textInfoParty.append("Attendre la début de la partie"); // créer un ThreadClient et lancer son exécution System.out.println("avant démarrage du thread"); ThreadClient threadClient = new ThreadClient(this); threadClient.start(); System.out.println("Apres le thread"); } } catch (IOException err) { System.err.println("Problème de connection serveur: " + err.getMessage() + "\n.Arrêt..."); System.exit(1); } } else if (e.getSource() == butPlay) { try { // envoyer requête PLAY (paramètre : contenu de textPlay) oos.writeInt(JungleServer.REQ_PLAY); oos.writeObject(textPlay.getText()); oos.flush(); orderSent = true; butPlay.setEnabled(false); textPlay.setEnabled(false); // mettre orderSent à true // bloquer le bouton play et le textfiled associé } catch (IOException err) { System.err.println("Problème connection serveur: " + err.getMessage() + "\n.Arrêt..."); System.exit(1); } } else if (e.getSource() == butQuit) { try { oos.close(); ois.close(); setConnectionPanel(); comm = null; } catch (IOException err) { System.err.println("Problème connection serveur: " + err.getMessage() + "\n.Arrêt..."); System.exit(1); } } }
// Checks the current state and sets the enables/disables // accordingly public void run() { switch (connectionStatus) { case DISCONNECTED: connectButton.setEnabled(true); disconnectButton.setEnabled(false); ipField.setEnabled(true); portField.setEnabled(true); hostOption.setEnabled(true); guestOption.setEnabled(true); chatLine.setText(""); chatLine.setEnabled(false); statusColor.setBackground(Color.red); break; case DISCONNECTING: connectButton.setEnabled(false); disconnectButton.setEnabled(false); ipField.setEnabled(false); portField.setEnabled(false); hostOption.setEnabled(false); guestOption.setEnabled(false); chatLine.setEnabled(false); statusColor.setBackground(Color.orange); break; case CONNECTED: connectButton.setEnabled(false); disconnectButton.setEnabled(true); ipField.setEnabled(false); portField.setEnabled(false); hostOption.setEnabled(false); guestOption.setEnabled(false); chatLine.setEnabled(true); statusColor.setBackground(Color.green); break; case BEGIN_CONNECT: connectButton.setEnabled(false); disconnectButton.setEnabled(false); ipField.setEnabled(false); portField.setEnabled(false); hostOption.setEnabled(false); guestOption.setEnabled(false); chatLine.setEnabled(false); chatLine.grabFocus(); statusColor.setBackground(Color.orange); break; } // Make sure that the button/text field states are consistent // with the internal states ipField.setText(hostIP); portField.setText((new Integer(port)).toString()); hostOption.setSelected(isHost); guestOption.setSelected(!isHost); statusField.setText(statusString); chatText.append(toAppend.toString()); toAppend.setLength(0); mainFrame.repaint(); }
@Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("下棋")) { audience.setEnabled(false); fighter.setEnabled(false); begin.setEnabled(true); // JOptionPane.showMessageDialog(null, "下棋"); System.out.println("下棋"); try { System.out.println("客户端发送下棋指令"); out66.writeObject("对手"); out66.flush(); out66.writeObject(new char[0][0]); out66.flush(); out66.writeObject(new boolean[0][0]); out66.flush(); } catch (IOException e1) { e1.printStackTrace(); } } if (e.getActionCommand().equals("观看")) { submit.setEnabled(false); regret.setEnabled(false); audience.setEnabled(false); fighter.setEnabled(false); // JOptionPane.showMessageDialog(null, "观看"); System.out.println("观看"); try { out66.writeObject("观众"); out66.flush(); out66.writeObject(stateList.get(stateList.size() - 1)); out66.flush(); out66.writeObject(takenList.get(takenList.size() - 1)); out66.flush(); } catch (IOException e1) { e1.printStackTrace(); } } /*if (e.getActionCommand().equals("人机对弈")) { audience.setEnabled(false); fighter.setEnabled(false); AIPlayer.setEnabled(false); begin.setEnabled(true); JOptionPane.showMessageDialog(null, "人机对弈"); }*/ if (e.getActionCommand().equals("发送")) { // JOptionPane.showMessageDialog(null, "发送"); System.out.println("发送"); String str = myRole + ": " + " " + jt1.getText() + "\n"; try { out99.writeObject(" " + str); out99.flush(); out99.writeObject(new char[8][8]); out99.flush(); out99.writeObject(new boolean[8][8]); out99.flush(); } catch (IOException e1) { e1.printStackTrace(); } jt2.append(str); jt1.setText(""); } if (e.getActionCommand().equals("取消")) { // JOptionPane.showMessageDialog(null, "取消"); System.out.println("取消"); jt1.setText(""); } if (e.getActionCommand().equals("悔棋")) { // JOptionPane.showMessageDialog(null, "悔棋"); System.out.println("悔棋"); try { out66.writeObject("请求悔棋"); out66.flush(); out66.writeObject(new char[8][8]); out66.flush(); out66.writeObject(new boolean[8][8]); out66.flush(); } catch (IOException e1) { e1.printStackTrace(); } // RegretChess(); // ShowChessNumber(); } if (e.getActionCommand().equals("退出")) { int quit = JOptionPane.showConfirmDialog(null, "您确定要强制退出吗?", "请确认您的选择", JOptionPane.YES_NO_OPTION); if (quit == JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(null, "已强制退出"); System.exit(0); } else return; } if (e.getActionCommand().equals("开始")) { begin.setEnabled(false); System.out.println("客户端发送开始指令"); // JOptionPane.showMessageDialog(null, "开始"); try { out66.writeObject("请求开始"); out66.flush(); out66.writeObject(stateList.get(stateList.size() - 1)); out66.flush(); out66.writeObject(takenList.get(takenList.size() - 1)); out66.flush(); } catch (IOException e1) { e1.printStackTrace(); } Begin(); if (kind == "黑") { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) if (cell[i][j].taken == false) { CheckPlace(cell[i][j]); if (canPut) { cell[i][j].ChangeBackground(); canPut = false; } } } } if (e.getActionCommand().equals("存盘")) { // JOptionPane.showMessageDialog(null, "存盘"); System.out.println("存盘"); try { System.out.println(); out.writeObject(stateList); out.flush(); out.close(); } catch (IOException e1) { e1.printStackTrace(); } } }
public void PintaMensaje(String mensaje) { textarea1.append("\n============================================"); textarea1.append("\n" + mensaje); textarea1.append("\n============================================"); }
public void actionPerformed(ActionEvent evt) { String arg = evt.getActionCommand(); if (arg.equals("Query")) { // 用户按下Query按钮 ResultSet rs = null; try { String author = (String) authors.getSelectedItem(); String publisher = (String) publishers.getSelectedItem(); if (!author.equals("Any") && !publisher.equals("Any")) { if (authorPublisherQueryStmt == null) { // 根据用户选择的出版社名和作者名查询相关的书名和书价 String authorPublisherQuery = "SELECT Books.Price, Books.Title " + "FROM Books, BooksAuthors, Authors, Publishers " + "WHERE Authors.Author_Id = BooksAuthors.Author_Id AND " + "BooksAuthors.ISBN = Books.ISBN AND " + "Books.Publisher_Id = Publishers.Publisher_Id AND " + "Authors.Name = ? AND " + "Publishers.Name = ?"; authorPublisherQueryStmt = con.prepareStatement(authorPublisherQuery); } authorPublisherQueryStmt.setString(1, author); authorPublisherQueryStmt.setString(2, publisher); rs = authorPublisherQueryStmt.executeQuery(); } else if (!author.equals("Any") && publisher.equals("Any")) { if (authorQueryStmt == null) { // 根据用户选择的作者名查询相关的书名和书价 String authorQuery = "SELECT Books.Price, Books.Title " + "FROM Books, BooksAuthors, Authors " + "WHERE Authors.Author_Id = BooksAuthors.Author_Id AND " + "BooksAuthors.ISBN = Books.ISBN AND " + "Authors.Name = ?"; authorQueryStmt = con.prepareStatement(authorQuery); } authorQueryStmt.setString(1, author); rs = authorQueryStmt.executeQuery(); } else if (author.equals("Any") && !publisher.equals("Any")) { if (publisherQueryStmt == null) { // 根据用户选择的出版社名查询相关的书名和书价 String publisherQuery = "SELECT Books.Price, Books.Title " + "FROM Books, Publishers " + "WHERE Books.Publisher_Id = Publishers.Publisher_Id AND " + "Publishers.Name = ?"; publisherQueryStmt = con.prepareStatement(publisherQuery); } publisherQueryStmt.setString(1, publisher); rs = publisherQueryStmt.executeQuery(); } else { if (allQueryStmt == null) { // 若用户未选任何信息,则输出所有的书名和对应的书价 String allQuery = "SELECT Books.Price, Books.Title FROM Books"; allQueryStmt = con.prepareStatement(allQuery); } rs = allQueryStmt.executeQuery(); } result.setText(""); while (rs.next()) result.append(rs.getString(1) + " | " + rs.getString(2) + "\n"); rs.close(); } catch (Exception e) { result.setText("Error " + e); } } else if (arg.equals("Change prices")) { // 用户选择“Change prices”按钮 String publisher = (String) publishers.getSelectedItem(); if (publisher.equals("Any")) result.setText("I am sorry, but I cannot do that."); else try { // 根据用户输入的新的书价更新Books表的数据 String updateStatement = "UPDATE Books " + "SET Price = Price + " + priceChange.getText() + " WHERE Books.Publisher_Id = " + "(SELECT Publisher_Id FROM Publishers WHERE Name = '" + publisher + "')"; int r = stmt.executeUpdate(updateStatement); result.setText(r + " records updated."); } catch (Exception e) { result.setText("Error " + e); } } }