2013-06-12 92 views
0

我有一個客戶端 - 服務器通信代碼。但是,我確實希望多個客戶端與服務器通信而不是其他客戶端,我應該如何實現它?如何實現多個客戶端 - 服務器聊天

// This is server code: 

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

class ServerFile extends JFrame { 
    private JTextField usertext; 
    private JTextArea chatwindow; 
    private ObjectOutputStream output; 
    private ObjectInputStream input; 
    private ServerSocket server; 
    private Socket connection; 

    public ServerFile() { 
     super("Admin"); 
     usertext = new JTextField(); 
     usertext.setEditable(false); 
     usertext.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent event) { 
       sendmessage(event.getActionCommand()); 
       usertext.setText(""); 
      } 
     }); 
     add(usertext, BorderLayout.SOUTH); 
     chatwindow = new JTextArea(); 
     add(new JScrollPane(chatwindow)); 
     setSize(300, 250); 
     setVisible(true); 
    } 

    public void startrunning() { 
     try { 
      server = new ServerSocket(6789, 100); 
      while (true) { 
       try { 
        waitForConnection(); 
        setupstream(); 
        whilechatting(); 
       } catch (Exception e) { 
        System.out 
          .println("\nYou have an error in conversation with client"); 
       } finally { 
        closecrap(); 
       } 
      } 
     } catch (Exception e) { 
      System.out.println("\nYou have an error in connecting with client"); 
     } 
    } 

    private void waitForConnection() throws IOException { 

     showmessage("\nWaiting for someone to connect"); 
     connection = server.accept(); 
     showmessage("\nNow connected to " 
       + connection.getInetAddress().getHostName()); 
    } 

    private void setupstream() throws IOException { 

     output = new ObjectOutputStream(connection.getOutputStream()); 
     output.flush(); 
     input = new ObjectInputStream(connection.getInputStream()); 
     showmessage("\nStreams are setup"); 
    } 

    private void whilechatting() throws IOException { 

     String message = "\nYou are now connected "; 
     sendmessage(message); 
     ableToType(true); 
     do { 
      try { 
       message = (String) input.readObject(); 
       showmessage(message); 
      } catch (Exception e) { 
       System.out.println("\nError in reading message"); 
      } 
     } while (!message.equals("CLIENT-END")); 
    } 

    private void closecrap() { 

     showmessage("\nClosing connection"); 
     ableToType(false); 
     try { 
      output.close(); 
      input.close(); 
      connection.close(); 
     } catch (Exception e) { 
      System.out.println("\nError in closing server"); 

     } 
    } 

    private void sendmessage(String message) { 

     try { 
      chatwindow.append("\nSERVER: " + message); 
      output.writeObject("\nSERVER: " + message); 
      output.flush(); 
     } catch (Exception e) { 
      chatwindow.append("\nError in sending message from server side"); 
     } 
    } 

    private void showmessage(final String text) { 

     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       chatwindow.append("\n" + text); 
      } 
     }); 
    } 

    private void ableToType(final boolean tof) { 

     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       usertext.setEditable(tof); 
      } 
     }); 
    } 

} 

public class Server { 
    public static void main(String args[]) { 
     ServerFile server1 = new ServerFile(); 
     server1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     server1.startrunning(); 
    } 
} 



// and this is the client code: 

import javax.swing.JFrame; 
import java.net.*; 
import java.io.*; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

class ClientFile extends JFrame { 

    private static final long serialVersionUID = 1L; 
    private JTextField usertext; 
     private JTextArea chatwindow; 
     private ObjectOutputStream output; 
     private ObjectInputStream input; 
     private String message=""; 
     private String serverIP; 
     private ServerSocket server; 
     private Socket connection; 

     public ClientFile(String host) 
     { 
      super("Client"); 
      serverIP=host; 
      usertext= new JTextField(); 
      usertext.setEditable(false); 
      usertext.addActionListener(new ActionListener(){ 
       public void actionPerformed(ActionEvent event){ 
        sendmessage(event.getActionCommand()); 
        usertext.setText(""); 
       } 
      } 
     ); 

      add(usertext,BorderLayout.SOUTH); 
      chatwindow= new JTextArea(); 
      add(new JScrollPane(chatwindow)); 
      setSize(300,250); 
      setVisible(true); 
     } 

     public void startrunning() { 
      try { 
       connecttoserver(); 
       setupstream(); 
       whilechatting(); 
      } 
      catch(Exception e){ 
       System.out.println("\nYou have an error in coversation with server"); 
      } 
      finally{ 
       closecrap(); 
      } 
     } 

     private void connecttoserver() throws IOException{ 
      showmessage("\nAttempting connection"); 
      connection = new Socket(InetAddress.getByName("127.0.0.1"),6789);   
      showmessage("\nConnected to "+connection.getInetAddress().getHostName()); 
     } 

     private void setupstream() throws IOException{ 
      output= new ObjectOutputStream(connection.getOutputStream()); 
      output.flush(); 
      input= new ObjectInputStream(connection.getInputStream()); 
      showmessage("\nStreams are good to go"); 
     } 

     private void whilechatting()throws IOException{ 
      ableToType(true); 
      do { 
       try{ 
        message = (String)input.readObject(); 
        showmessage(message); 
       } 
       catch(Exception e){ 
        System.out.println("\nError in writing message"); 
       } 
      } while(!message.equals("SERVER - END")); 
     } 

     private void closecrap(){ 
      showmessage("\nClosing...."); 
      ableToType(false); 
      try{ 
       output.close(); 
       input.close(); 
       connection.close(); 
      } 
      catch(Exception e){ 
       System.out.println("\nError in closing client"); 
      } 
     } 

     private void sendmessage(String message){ 
      try{ 
       chatwindow.append("\nCLIENT: "+message); 
       output.writeObject("\nCLIENT: "+message); 
       output.flush(); 
      } 
      catch(Exception e){ 
       chatwindow.append("\nError in sending message from client side"); 
      } 
     } 

     private void showmessage(final String m){ 
      SwingUtilities.invokeLater(new Runnable(){ 
      public void run(){ 
       chatwindow.append("\n"+m); 
      }}); 
     } 

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

public class Client { 
     public static void main(String args[]) 
     { 
      ClientFile obj2= new ClientFile("127.0.0.1"); 
      obj2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      obj2.startrunning(); 

     }   
} 

應用多線程是一個很好的解決方案,但應用時,我有得到連接只有一個客戶端和一個服務器之間extablished。請幫我做這件事

回答

2

應用多線程是一個很好的解決方案,但應用時,我有得到連接只有一個客戶端和一個服務器之間extablished。請幫我做這件事

我沒打通(因此選中)所有的代碼,但我注意到一件事:

startrunning()功能您:

  • 在英輝循環創建服務器套接字
    • 等待一個新的連接
    • 有一個新的連接呼叫時setupstream()
    • 並使用whilechatting()

那麼,你將只獲得一個新的連接,將獲得它的流設置和聊天。您只能有一個線程爲您的客戶提供服務,因此只有第一個線程才能得到服務,直到它釋放線程以便其他人可以連接。

而應該做的:

  • 在英輝循環創建服務器套接字
    • 等待一個新的連接
    • 時,有一個新的連接:
    • 創建該連接的新線程
    • 致電setupstream()
    • 和使用whilechatting()

有每個客戶將得到催生成自己愜意的線程,而主線程處於無限循環等待新的客戶聊天。

HTH

+0

我做了你所說的,創建了另一個服務器線程。但是,只有在連接的前兩臺服務器 - 客戶端之間纔有流連接。接下來的兩個客戶端服務器不工作 – Deepali

+0

在setupstream()方法中,output = new ObjectOutputStream(connection.getOutputStream());這給出了一個空指針異常 – Deepali