2015-09-18 192 views
2

如何在Java中建立多個客戶端到單個服務器的連接?這是迄今爲止的代碼。當我運行程序時,服務器可以讀取來自客戶端的輸入,但只能讀取一個客戶端。另外當我點擊發送消息。服務器可以讀取它,但消息不顯示在客戶端的顯示框上。我如何解決這些問題?如何將多個客戶端連接到單臺服務器?

ServerThread類

import java.net.*; 
import java.io.*; 

public class ServerThread extends Thread 
{ 
    private static Thread[] listOfThreads = null; 
    private static ServerThread thread = null; 
    private Socket connection; 
    private PrintWriter output; 
    private BufferedReader input; 
    private ThreadGroup clientGroup; 

public ServerThread(ThreadGroup threadGroup, Socket connection) 
{ 

    super(threadGroup, "Connection to ChatClient"); 
    clientGroup = threadGroup; 
    this.connection = connection; 
    try {  
     output = new PrintWriter(connection.getOutputStream(), true); 
     input = new BufferedReader(new InputStreamReader (connection.getInputStream())); 
    } 
    catch(IOException e) { 
     System.out.println("Error while getting input and output stream from socket"); 
    } 
} 
public void run() { 
    try 
    {   
     String data = input.readLine(); 
     while(data != null) 
     { 

      System.out.println(data); 
      int numOfThreads = clientGroup.activeCount();    
       thread.sendToAllClients(data) ; 
      clientGroup.enumerate(listOfThreads);     

      for (int i = 0; i < numOfThreads; i++) 
      {    
       ServerThreadThai thread = (ServerThreadThai) listOfThreads[i];     
       thread.sendToAllClients(data) ; 
      } 

      data = input.readLine(); 
     } 
    } 
    catch(IOException e) { 
     System.out.println("Client has been disconnected"); 
    } 
} 
public void sendToAllClients(String data) { 
    output.println(data); 
} 
} 

的ChatServer

import java.net.*; 
import java.io.*; 

class ChatServer 
{ 
public static void main(String[] args) 
{ 
    ServerSocket serverSocket = null; 
    ThreadGroup myThreadGroup = new ThreadGroup("Contain chat client threads"); 
    try 
    {  
     serverSocket = new ServerSocket(12); // Create Server Socket 
     System.out.println("Server started. Waitting for client"); 
     while (true) 
     {   
      Socket connectionTo = serverSocket.accept();   
      System.out.println("Received a connection from a client");    
      new ServerThread(myThreadGroup, connectionTo).run();    
     } 
    } 
    catch (IOException e) { 
    System.out.println("Could not use this port"); 
    System.exit(1); 
    } 
} 
} 

ChatClient

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

class ClientFrame extends JFrame implements ActionListener 
{ 
private PrintWriter output; 
private BufferedReader input; 
private JButton sendButton, exitButton; 
private JTextArea display; 
private JTextField dataIn, userName; 

public ClientFrame(String host) 
{ 

    try 
    {  
     Socket socket = new Socket(host, 12); 
     input = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
     output = new PrintWriter(socket.getOutputStream(), true);  
    } 
    catch (UnknownHostException e) 
    { 
     System.out.println("Unknow host"); 
     System.exit(1); 
    } 
    catch(IOException e) 
    { 
     System.out.println("Error open connection"); 
     int width = 500, height = 400; 
    } 

    Toolkit tk = getToolkit(); 
    Dimension screen = tk.getScreenSize(); 
    int width = 500, height = 400; 
    setBounds((screen.width - width)/2, (screen.height - height)/2, width, height); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 

    dataIn = new JTextField(20); 

    userName = new JTextField(5); 
    userName.setText("Name"); 

    sendButton = new JButton("Send text"); 
    exitButton = new JButton("Exit"); 

    sendButton.addActionListener(this); 
    exitButton.addActionListener(this); 

    JPanel p = new JPanel(); 
    p.setLayout(new FlowLayout()); 
    p.add(dataIn); 
    p.add(sendButton); 
    p.add(exitButton); 
    p.add(userName); 

    display = new JTextArea(); 
    Container c = getContentPane(); 
    c.setLayout(new BorderLayout()); 

    c.add(display, BorderLayout.CENTER); 
    c.add(p, BorderLayout.SOUTH); 
    setVisible(true); 
} 

public void actionPerformed (ActionEvent e) 
{ 
    JButton src = (JButton) e.getSource(); 
    if(src == sendButton) 
    { 
     if(dataIn.getText().equals("")) 
      return; 

      output.println(userName.getText() + ": " + dataIn.getText()); 
      dataIn.setText("");   
      dataIn.requestFocus(true); 
    } 
    else 
    System.exit(0); 
} 


public void process() 
{ 
    try 
    { 
      String data = input.readLine(); 
      //while (data != null); 
      do 
      { 
       display.append("Welcome"); 
       data = input.readLine();   
       display.append(data + "\n"); 
      } 
      while (data != null); 
    } 
    catch(IOException e) 
    { 
     System.out.println("Error while reading from server"); 
    } 
} 
} 

public class ChatClient{ 
public static void main(String[] args) 
{ 
    String host= "127.0.0.1";  
    ClientFrame client = new ClientFrame(host); 
    client.process(); 


} 
} 

回答

3

的主要問題是,當您收到新的連接請求不要啓動任何服務器上的線程。爲了產生一個新線程,你需要調用方法start()而不是run()。

嘗試修改此行:

new ServerThread(myThreadGroup, connectionTo).run(); 

這一行:

new ServerThread(myThreadGroup, connectionTo).start(); 

仍有可能在代碼中其他錯誤,但。

相關問題