2013-11-28 135 views
0

所以我有這樣的服務器代碼:(順便說一句,這是一個即時通訊程序)允許多個Clientst連接到該服務器

import java.io.*; 
import java.net.*; 
import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.html.HTMLDocument; 
import javax.swing.text.html.HTMLEditorKit; 

public class Server extends JFrame{ 
    /** 
    * 
    */ 
    private static final long serialVersionUID = -7849253481287712961L; 
    static String name =JOptionPane.showInputDialog(null, "Enter in your name.", "Name", JOptionPane.QUESTION_MESSAGE); 
    boolean afk = false; 
    double ver = 1.1; 
    private JTextField userText; 
    private ObjectOutputStream output; 

    private ObjectInputStream input; 
    private ServerSocket server; 
    private Socket connection; 
    private JTextPane images; 
    private JScrollPane jsp = new JScrollPane(); 

    public Server(){ 
     super(name+" - IM Server"); 
     images = new JTextPane(); 
     images.setContentType("text/html"); 
     userText = new JTextField(); 
     userText.setEditable(false); 
     images.setContentType("text/html"); 
     if(name.isEmpty()){ 
      JOptionPane.showMessageDialog(null, "Name cannot be blank!", "ERROR!", JOptionPane.ERROR_MESSAGE); 
      System.exit(0); 
     } 
     userText.addActionListener(
     new ActionListener(){ 
      public void actionPerformed(ActionEvent event){ 
       sendMessage(event.getActionCommand()); 
       userText.setText(""); 
      } 
     } 
    ); 
     add(userText, BorderLayout.NORTH); 
     jsp.setViewportView(images); 
     add(jsp); 
     images.setEditable(false); 
     setSize(700,400); 
     setVisible(true); 
     ImageIcon logo = new javax.swing.ImageIcon(getClass().getResource("CHAT.png")); 
     setIconImage(logo.getImage()); 
    } 


    public void startRunning(){ 
     try{ 
     server = new ServerSocket(6789, 100); 
     String OS = System.getProperty("os.name").toLowerCase(); 
     if(OS.contains("windows")){ 
      showMessage("Open command prompt, and type ipconfig, find the right ip, and tell your friend that ip to connect!\n"); 
     }else if(OS.contains("mac")){ 
      showMessage("Open your network settings, find your ip, and tell your friend that ip to connect!\n"); 
     }else{ 
      showMessage("Looks like you're not running windows or mac. Find your ip address however you do, and tell your friend to connect using it!\n"); 
     } 
     while(true){ 
      try{ 
       waitForConnection(); 
       setupStreams(); 
       whileChatting(); 
      }catch(EOFException eofException){ 
       showMessage("\n Server stopped! "); 
      }finally{ 
       closestuff(); 
      } 
     } 
     }catch(IOException ioException){ 
     ioException.printStackTrace(); 
     } 
    } 


    private void waitForConnection() throws IOException{ 
     showMessage("Running server on *.6789 \n"); 
     showMessage("Waiting for someone to connect... \n"); 
     connection = server.accept(); 
     images.setText(""); 
     showMessage(" Now connected to " + connection.getInetAddress().getHostName()); 
     showMessage("This is where images and text will show up.\nTo send an image, type\nimgURLHERE\nand replace URLHERE with the URL of the image.\nIt CANNOT have SPACES or EXTRA TEXT.\nalso, you can use\nHTML stuff :D"); 

    } 


    private void setupStreams() throws IOException{ 
     output = new ObjectOutputStream(connection.getOutputStream()); 
     output.flush(); 
     input = new ObjectInputStream(connection.getInputStream()); 
     showMessage("\n Done! \n"); 
    } 


    private void whileChatting() throws IOException{ 
     String message = " Connected! "; 
     sendMessage(message); 
     ableToType(true); 
     do{ 
     try{ 
      message = (String) input.readObject(); 
      showMessage("\n" + message); 
     }catch(ClassNotFoundException classNotFoundException){ 
      showMessage("\n Cannot get other user's message."); 
     } 
     }while(!message.equals("CLIENT - END")); 
    } 


    private void closestuff(){ 
     showMessage("\n Closing connections... \n"); 
     ableToType(false); 
     try{ 
     output.close(); 
     input.close(); 
     connection.close(); 
     }catch(IOException ioException){ 
     ioException.printStackTrace(); 
     } 
    } 


    private void sendMessage(String message){ 
     try{ 
      name = "<html><font color=red>"+name; 
      message = message.replace("*dissaproval*", "ಠ_ಠ"); 
      message = message.replace("*tbf*", "(╯°□°)╯︵ ┻━┻"); 
      message = message.replace("*tableflip*", "(╯°□°)╯︵ ┻━┻"); 
      if(message.contains("afk") & afk == false){ 
       output.writeObject(name+" is now afk."+"</font></html>"); 
       showMessage("\n"+name+" is now afk."+"</font></html>"); 
       afk = true; 
      }else if(message.contains("afk") & afk == true){ 
       output.writeObject(name+" is no longer afk."+"</font></html>"); 
       showMessage("\n"+name+" is no longer afk."+"</font></html>"); 
       output.writeObject(name + " - " + message+"</font></html>"); 
       afk = false; 
      }else if(afk == true & !message.contains("afk")){ 
       output.writeObject(name+" is no longer afk."+"</font></html>"); 
       output.writeObject(name + " - " + message+"</font></html>"); 
       showMessage("\n"+name+" is no longer afk."+"</font></html>"); 
       showMessage("\n"+name+" - " + message+"</font></html>"); 
       afk = false; 
      }else if(message.contains("img")){ 
       message = message.replaceAll("img", ""); 
       message = "</font></html><html><img src='"+message+"'/>\n </html>"; 
       showMessage("\n"+name+" - "+message+"</font></html>"); 
       output.writeObject(name + " - " + message+"</font></html>"); 
      }else if(message.isEmpty()){ 
      }else{ 
       output.writeObject(name + " - " + message+"</font></html>"); 
       showMessage("\n"+name+" - " + message+"</font></html>"); 
      } 
      output.flush(); 

      }catch(IOException ioException){ 
      } 
     } 


    private void showMessage(final String text){ 
     SwingUtilities.invokeLater(
     new Runnable(){ 
      public void run(){ 
       userText.requestFocus(); 
       HTMLDocument doc = (HTMLDocument)images.getDocument(); 
       HTMLEditorKit editorKit = (HTMLEditorKit)images.getEditorKit(); 
       try { 
        try { 
         editorKit.insertHTML(doc, doc.getLength(), text, 0, 0, null); 
         images.setCaretPosition(images.getDocument().getLength()); 
        } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
      } catch (BadLocationException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      } 
     } 
    ); 
    } 


    private void ableToType(final boolean tof){ 
     SwingUtilities.invokeLater(
     new Runnable(){ 
      public void run(){ 
       userText.setEditable(tof); 
      } 
     } 
    ); 
    } 

} 

與此客戶端代碼:

import java.io.*; 
import java.net.*; 
import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.html.HTMLDocument; 
import javax.swing.text.html.HTMLEditorKit; 
public class Client extends JFrame{ 
    /** 
    * 
    */ 
    private static final long serialVersionUID = 1897693519598758260L; 
static String name =JOptionPane.showInputDialog(null, "Enter in your name.", "Name", JOptionPane.QUESTION_MESSAGE); 
    boolean started = true; 
    boolean afk = false; 
    double ver = (1); 
    private JTextField userText; 
    private ObjectOutputStream output; 
    private ObjectInputStream input; 
    private String message = ""; 
    private String serverIP; 
    private Socket connection; 
    private JTextPane images; 
    private JScrollPane jsp = new JScrollPane(); 
    static String IP =JOptionPane.showInputDialog(null, "Enter in the IP (WITHOUT PORT) to connect to.", "IP", JOptionPane.QUESTION_MESSAGE); 
    public Client(String host){ 
     super(name+" - IM Client"); 
     serverIP = IP; 
     if(serverIP.isEmpty() || name.isEmpty()){ 
      JOptionPane.showMessageDialog(null, "Name and/or IP can not be blank!!!", "ERROR!", JOptionPane.ERROR_MESSAGE); 
      System.exit(0); 
     } 
     userText = new JTextField(); 
     images = new JTextPane(); 
     userText.setEditable(false); 
     userText.addActionListener(
     new ActionListener(){ 
      public void actionPerformed(ActionEvent event){ 
       sendMessage(event.getActionCommand()); 
       userText.setText(""); 
      } 
     } 
    ); 
     add(userText, BorderLayout.NORTH); 
     jsp.setViewportView(images); 
     add(jsp); 
     images.setEditable(false); 
     images.setEditable(false); 
     images.setContentType("text/html"); 
     HTMLDocument doc = (HTMLDocument)images.getDocument(); 
     images.setContentType("text/html"); 
     try { 
     doc.insertString(0, "This is where images and text will show up.\nTo send an image, type\nimgURLHERE\nand replace URLHERE with the URL of the image.\nIt CANNOT have SPACES or EXTRA TEXT.\nalso, you can use\nHTML stuff :D", null); 
    } catch (BadLocationException e) { 
     e.printStackTrace(); 
    } 
     setSize(700,400); 
     setVisible(true); 
     ImageIcon logo = new javax.swing.ImageIcon(getClass().getResource("CHAT.png")); 
     setIconImage(logo.getImage()); 
    } 
    public void startRunning(){ 
     try{ 
     connectToServer(); 
     setupStreams(); 
     whileChatting(); 
     }catch(EOFException eofException){ 
     showMessage("\n Client terminated connection."); 
     }catch(IOException ioException){ 
     ioException.printStackTrace(); 
     }finally{ 
     closestuff(); 
     } 
    } 
    private void connectToServer() throws IOException{ 
     showMessage("Attempting to connect... \n"); 
     connection = new Socket(InetAddress.getByName(serverIP), 6789); 
     showMessage("Connected to: " + connection.getInetAddress().getHostName()); 
    } 
    private void setupStreams() throws IOException{ 
     output = new ObjectOutputStream(connection.getOutputStream()); 
     output.flush(); 
     input = new ObjectInputStream(connection.getInputStream()); 
     showMessage("\n Done! \n"); 
    } 
    private void whileChatting() throws IOException{ 
     ableToType(true); 
     do{ 
     try{ 
      message = (String) input.readObject(); 
      showMessage("\n" + message); 
     }catch(ClassNotFoundException classNotfoundException){ 
      showMessage("\n I dont know that object type."); 
     } 
     }while(!message.equals("SERVER - END"));{ 
     } 
    } 
    private void closestuff(){ 
     showMessage("\n Shutting down..."); 
     ableToType(false); 
     try{ 
     output.close(); 
     input.close(); 
     connection.close(); 
     }catch(IOException ioException){ 
     ioException.printStackTrace(); 
     } 
    } 
private void sendMessage(String message){ 
     try{ 
     name = "<html><font color=blue>"+name; 
     message = message.replace("*dissaproval*", "ಠ_ಠ"); 
     message = message.replace("*tbf*", "(╯°□°)╯︵ ┻━┻"); 
     message = message.replace("*tableflip*", "(╯°□°)╯︵ ┻━┻"); 
     if(message.contains("afk") & afk == false){ 
      output.writeObject(name+" is now afk."+"</font></html>"); 
      showMessage("\n"+name+" is now afk."+"</font></html>"); 
      afk = true; 
     }else if(message.contains("afk") & afk == true){ 
      output.writeObject(name+" is no longer afk."+"</font></html>"); 
      showMessage("\n"+name+" is no longer afk."+"</font></html>"); 
      output.writeObject(name + " - " + message+"</font></html>"); 
      afk = false; 
     }else if(afk == true & !message.contains("afk")){ 
      output.writeObject(name+" is no longer afk."+"</font></html>"); 
      output.writeObject(name + " - " + message+"</font></html>"); 
      showMessage("\n"+name+" is no longer afk."+"</font></html>"); 
      showMessage("\n"+name+" - " + message+"</font></html>"); 
      afk = false; 
     }else if(message.contains("img")){ 
      message = message.replaceAll("img", ""); 
      message = "</font></html><html><img src='"+message+"'/>\n </html>"; 
      showMessage("\n"+name+" - "+message+"</font></html>"); 
      output.writeObject(name + " - " + message+"</font></html>"); 
     }else if(message.isEmpty()){ 
     }else{ 
      output.writeObject(name + " - " + message+"</font></html>"); 
      showMessage("\n"+name+" - " + message+"</font></html>"); 

     output.flush(); 

     }}catch(IOException ioException){ 
     } 
    } 
    private void showMessage(final String m){ 
     SwingUtilities.invokeLater(
     new Runnable(){ 
      public void run(){ 
       userText.requestFocus(); 
       HTMLDocument doc = (HTMLDocument)images.getDocument(); 
       HTMLEditorKit editorKit = (HTMLEditorKit)images.getEditorKit(); 

      try { 
       try { 
        editorKit.insertHTML(doc, doc.getLength(), m, 0, 0, null); 
        images.setCaretPosition(images.getDocument().getLength()); 
       } catch (BadLocationException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      } 
     } 
    ); 
    } 
    private void ableToType(final boolean tof){ 
     SwingUtilities.invokeLater(
     new Runnable(){ 
      public void run(){ 
       userText.setEditable(tof); 
      } 
     } 
    );  
    } 
} 

,我想知道如何讓多個客戶端連接到服務器。如果這太複雜,我很抱歉。我是否需要一個單獨的課程來接受客戶,或者我是否總是檢查客戶並接受他們?另外,我會如何做到這一點,所發送的信息將出現在所有的客戶端?再次,如果這太複雜,我很抱歉。

回答

0

在這裏看到的頁面Supporting Multiple Clients的底部,一般來說:

while (true) { 
    accept a connection; 
    create a thread to deal with the client; 
} 
相關問題