2015-09-18 33 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(); 

仍有可能在代码中其他错误,但。

相关问题