如何让多个客户端访问我的聊天室(Bucky的即时通讯工具)

时间:2013-05-10 01:14:43

标签: java swing chatroom

您好我下载了Bucky的Messager,而不是让多个客户端连接到它,它让他们等待连接到服务器。我怎么能这样做,以便多个客户端可以立即连接到服务器?如果你能为我编辑代码并告诉我要编辑什么,我会很高兴。这是代码:

Client.java:

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

public class Client extends JFrame{

   private JTextField userText;
   private JTextArea chatWindow;
   private ObjectOutputStream output;
   private ObjectInputStream input;
   private String message = "";
   private String serverIP;
   private Socket connection;

   //constructor
   public Client(String host){
      super("Client mofo!");
      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.NORTH);
      chatWindow = new JTextArea();
      add(new JScrollPane(chatWindow), BorderLayout.CENTER);
      setSize(300,150);
      setVisible(true);
   }

   //connect to server
   public void startRunning(){
      try{
         connectToServer();
         setupStreams();
         whileChatting();
      }catch(EOFException eofException){
         showMessage("\n Client terminated connection");
      }catch(IOException ioException){
         ioException.printStackTrace();
      }finally{
         closeCrap();
      }
   }

   //connect to server
   private void connectToServer() throws IOException{
      showMessage("Attempting connection... \n");
      connection = new Socket(InetAddress.getByName(serverIP), 6789);
      showMessage("Connected to: " + connection.getInetAddress().getHostName() );
   }

   //set up streams to send and receive messages
   private void setupStreams() throws IOException{
      output = new ObjectOutputStream(connection.getOutputStream());
      output.flush();
      input = new ObjectInputStream(connection.getInputStream());
      showMessage("\n Dude your streams are now good to go! \n");
   }

   //while chatting with server
   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"));
   }

   //close the streams and sockets
   private void closeCrap(){
      showMessage("\n closing crap down...");
      ableToType(false);
      try{
         output.close();
         input.close();
         connection.close();
      }catch(IOException ioException){
         ioException.printStackTrace();
      }
   }

   //send messages to server
   private void sendMessage(String message){
      try{
         output.writeObject("CLIENT - " + message);
         output.flush();
         showMessage("\nCLIENT - " + message);
      }catch(IOException ioException){
         chatWindow.append("\n something messed up sending message hoss!");
      }
   }

   //change/update chatWindow
   private void showMessage(final String m){
      SwingUtilities.invokeLater(
         new Runnable(){
            public void run(){
               chatWindow.append(m);
            }
         }
      );
   }

   //gives user permission to type crap into the text box
   private void ableToType(final boolean tof){
      SwingUtilities.invokeLater(
         new Runnable(){
            public void run(){
               userText.setEditable(tof);
            }
         }
      );      
   }
}

ClientTest.java:

import javax.swing.JFrame;

public class ClientTest {
   public static void main(String[] args) {
      Client charlie;
      charlie = new Client("127.0.0.1");
      charlie.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      charlie.startRunning();
   }
}

Server.java:

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

public class Server extends JFrame{

   private JTextField userText;
   private JTextArea chatWindow;
   private ObjectOutputStream output;
   private ObjectInputStream input;
   private ServerSocket server;
   private Socket connection;

   //constructor
   public Server(){
      super("Buckys Instant Messenger");
      userText = new JTextField();
      userText.setEditable(false);
      userText.addActionListener(
         new ActionListener(){
            public void actionPerformed(ActionEvent event){
               sendMessage(event.getActionCommand());
               userText.setText("");
            }
         }
      );
      add(userText, BorderLayout.NORTH);
      chatWindow = new JTextArea();
      add(new JScrollPane(chatWindow));
      setSize(300,150);
      setVisible(true);
   }

   //set up and run the server
   public void startRunning(){
      try{
         server = new ServerSocket(6789, 100);
         while(true){
            try{
               waitForConnection();
               setupStreams();
               whileChatting();
            }catch(EOFException eofException){
               showMessage("\n Server ended the connection! ");
            }finally{
               closeCrap();
            }
         }
      }catch(IOException ioException){
         ioException.printStackTrace();
      }
   }

   //wait for connection, then display connection information
   private void waitForConnection() throws IOException{
      showMessage(" Waiting for someone to connect... \n");
      connection = server.accept();
      showMessage(" Now connected to " + connection.getInetAddress().getHostName());
   }

   //get stream to send and receive data
   private void setupStreams() throws IOException{
      output = new ObjectOutputStream(connection.getOutputStream());
      output.flush();
      input = new ObjectInputStream(connection.getInputStream());
      showMessage("\n Streams are now setup! \n");
   }

   //during the chat conversation
   private void whileChatting() throws IOException{
      String message = " You are now connected! ";
      sendMessage(message);
      ableToType(true);
      do{
         try{
            message = (String) input.readObject();
            showMessage("\n" + message);
         }catch(ClassNotFoundException classNotFoundException){
            showMessage("\n idk wtf that user sent!");
         }
      }while(!message.equals("CLIENT - END"));
   }

   //close streams and sockets after you are done chatting
   private void closeCrap(){
      showMessage("\n Closing connections... \n");
      ableToType(false);
      try{
         output.close();
         input.close();
         connection.close();
      }catch(IOException ioException){
         ioException.printStackTrace();
      }
   }

   //send a message to client
   private void sendMessage(String message){
      try{
         output.writeObject("SERVER - " + message);
         output.flush();
         showMessage("\nSERVER - " + message);
      }catch(IOException ioException){
         chatWindow.append("\n ERROR: DUDE I CANT SEND THAT MESSAGE");
      }
   }

   //updates chatWindow
   private void showMessage(final String text){
      SwingUtilities.invokeLater(
         new Runnable(){
            public void run(){
               chatWindow.append(text);
            }
         }
      );
   }

   //let the user type stuff into their box
   private void ableToType(final boolean tof){
      SwingUtilities.invokeLater(
         new Runnable(){
            public void run(){
               userText.setEditable(tof);
            }
         }
      );
   }

}

ServerTest.java:

import javax.swing.JFrame;

public class ServerTest {
   public static void main(String[] args) {
      Server sally = new Server();
      sally.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      sally.startRunning();
   }
}

2 个答案:

答案 0 :(得分:2)

以线程的形式制作serverTest.java,它将允许多个客户端

答案 1 :(得分:1)

  

您好我下载了Bucky的Messager,而不是让多个客户端连接到它,它让他们等待连接到服务器。我怎么能这样做,以便多个客户端可以立即连接到服务器?

如前所述,您当前借用的代码是单线程的:服务器只创建一个线程并在侦听该线程时阻塞其单个线程。该解决方案需要进行一些更改:

  • 首先,您需要在后台线程中使用Swing事件线程完成所有聊天。一个SwingWorker可以很好地完成这个工作,并且有很好的教程可以找到这个主题。
  • 接下来,服务器需要为每个连接创建一个新线程,以便在创建和通信连接时,它不会阻止服务器监听更多连接。
  

如果您能为我编辑代码并告诉我要编辑的内容,我会很高兴。这是代码:

这不会发生,因为你要求太多的志愿者。您将需要学习线程并尝试自己实现。我建议在将其移植到Swing GUI之前从非GUI套接字编程开始。