JAVA上服务器客户端聊天应用程序的示例

JAVA上服务器客户端聊天应用程序的示例,java,netbeans,client,chat,server,Java,Netbeans,Client,Chat,Server,我已经搜索了很长一段时间的服务器客户端聊天应用程序的例子,但我不能真正理解它们。他们中的许多人使用一个类并从中创建GUI,我不想直接从中复制。很多示例都没有真正解释如何将消息从客户端发送到服务器,然后服务器将消息发送到所有其他客户端 我正在使用NetBeans,我想知道是否有一些好的教程或例子可以帮助我做到这一点?这里是我刚才做的一个超级简单的例子,并对正在发生的事情进行了一些评论。连接到服务器的客户端可以键入服务器将打印的消息。这不是聊天程序,因为服务器接收消息,客户端发送消息。但希望你能更好

我已经搜索了很长一段时间的服务器客户端聊天应用程序的例子,但我不能真正理解它们。他们中的许多人使用一个类并从中创建GUI,我不想直接从中复制。很多示例都没有真正解释如何将消息从客户端发送到服务器,然后服务器将消息发送到所有其他客户端


我正在使用NetBeans,我想知道是否有一些好的教程或例子可以帮助我做到这一点?

这里是我刚才做的一个超级简单的例子,并对正在发生的事情进行了一些评论。连接到服务器的客户端可以键入服务器将打印的消息。这不是聊天程序,因为服务器接收消息,客户端发送消息。但希望你能更好地理解它:

服务器:

    import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class Main {

    public static DataInputStream in;
    public static DataOutputStream out;

    public static void main(String[] args) throws IOException {


    int port = 4444;
    ServerSocket server = null;
    Socket clientSocket = null;

    try {

    //start listening on port
    server = new ServerSocket(port);

    System.out.println("Listening on port: " + port);

    //Accept client
    clientSocket = server.accept();

    System.out.println("client Connected!");

    //initialize streams so we can send message
    in = new DataInputStream(clientSocket.getInputStream());
    out = new DataOutputStream(clientSocket.getOutputStream());

    String message = null;

        while (true) {
            // as soon as a message is being received, print it out!
            message = in.readUTF();
            System.out.println(message);
        }

    }
    catch (IOException e){
        e.printStackTrace();
        if (!server.isClosed()){server.close();}
        if (!clientSocket.isClosed()){clientSocket.close();}
    }

    }

}
客户:

    import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class Main  
{
   public static void main(String[] args) throws IOException {

       //declare a scanner so we can write a message
       Scanner keyboard = new Scanner(System.in);


       // localhost ip
       String ip = "127.0.0.1";
       int port = 4444;
       Socket socket = null;

       try {

       //connect
       socket = new Socket(ip, port);

       //initialize streams
       DataInputStream in = new DataInputStream(socket.getInputStream());
       DataOutputStream out = new DataOutputStream(socket.getOutputStream());


       while (true){
           System.out.print("\nMessage to server: ");
           //Write a message :)
           String message = keyboard.nextLine();
           //Send it to the server which will just print it out
           out.writeUTF(message);
       }

       }
       catch (IOException e){
           e.printStackTrace();
            if (!socket.isClosed()){socket.close();}
       }
   }
}

下面是多线程程序:服务器有两个类,客户端有一个。希望你喜欢

服务器主类:

    import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class Main {

    public static void main(String[] args) throws IOException {
        int MAXCLIENTS = 20;
        int port = 4444;
        ServerSocket server = null;
        Socket clientSocket = null;
        // An array of clientsConnected instances
        ClientThread[] clientsConnected = new ClientThread[MAXCLIENTS];

        try {
            server = new ServerSocket(port);
            System.out.println("listening on port: " + port);
        } catch (IOException e) {// TODO Auto-generated catch block
            e.printStackTrace();

        }

        while (true) {
            try {
                clientSocket = server.accept();

            } catch (IOException e) {
                e.printStackTrace();
                if (!server.isClosed()){server.close();}
                if (!clientSocket.isClosed()){clientSocket.close();}
            }

            System.out.println("Client connected!");

            for (int c = 0; c < clientsConnected.length; c++){
                if (clientsConnected[c] == null){
                    // if it is empty ( null) then start a new Thread, and pass the socket and the object of itself as parameter
                    (clientsConnected[c] = new ClientThread(clientSocket, clientsConnected)).start();
                    break; // have to break, else it will start 20 threads when the first client connects :P
                }
            }
        }

    }



}
我在eclipse中运行了服务器,并从CMD启动了两个客户端,如下所示:


提取所需的代码并将其放入App.java的main中。此外,这不是一个询问教程或示例的网站,而是一个特定编程问题的网站。感谢您提供的示例:一个问题是,如果我运行两个客户端实例,它们是否能够听到对方的声音?也就是说,如果我先运行client1,然后再运行client2,client1会听到client2发送给服务器的内容吗?不客气,对不起,这个服务器只接收一个客户端,如果一个服务器要处理多个客户端,那么你应该使用多线程。是的,我一直在研究这个问题。创建客户端类的对象并将其作为线程运行。但我不知道如何让他们从服务器上互相监听。你想让我发布一个简单的多线程服务器吗?如果没有问题,我一小时后就准备好了;非常感谢!!希望我能更多地理解这一点,以及它是如何与多线程一起工作的!非常感谢你花时间做这件事。我会做这个,然后尝试实现GUI到它!再次感谢你,你太棒了!!听起来是个好主意!不客气:我试图找到一种发送PM的方法,但我找不到方法,所以我必须在这里询问。在for循环中称为main的第一个类服务器中,检查数组中是否有客户机,如果没有,则只创建一个。您不应该每次接受套接字时都在列表中创建并添加一个客户端吗?因为在我看来,服务器似乎只能接受一个客户机。@Bojje,正如您所看到的,首先创建serversocket,然后是一个while循环。因此,当有人连接时,它将跳转到for循环并检查数组中是否有一个空元素。如果为空,则创建ClientThread类的新实例,然后将其存储在clientsConnected[c]数组中,并启动它。都在同一行中:。之后,由于所有这些都在while循环中,它将返回while循环的开始,即clientSocket=serverSocket.accept。这将继续下去:是的,这也是我不太明白的。它在一个while循环中,所以它不应该一直运行吗?如果serversocket接受新的套接字,为什么会跳转到for循环?当第二个客户被接受时,它是如何工作的?那么for循环什么都不做?编辑哦,别担心…我只是看错了。很抱歉
    import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;


public class ClientThread extends Thread{

    private ClientThread[] clientsConnected;
    private Socket socket = null;
    private DataInputStream in = null;
    private DataOutputStream out = null;
    private String clientName = null;

    //Constructor
     public ClientThread(Socket socket, ClientThread[] clientsConnected){
        this.socket = socket;
        this.clientsConnected = clientsConnected;
    }

    public void run(){
        try {
            // Streams :)
            in = new DataInputStream(socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());

            String message = null;

            clientName = in.readUTF();

            while (true){
                message = in.readUTF();

                for (int c = 0; c < clientsConnected.length; c++){
                    if (clientsConnected[c]!= null && clientsConnected[c].clientName != this.clientName){ //dont send message to your self ;)
                        clientsConnected[c].sendMessage(message, clientName); // loops through all the list and calls the objects sendMessage method.
                    }
                }

            }

        } catch (IOException e) {
            System.out.println("Client disconnected!");
            this.clientsConnected = null;
        }
    }
    // Every instance of this class ( the client ) will have this method.
    private void sendMessage(String mess, String name){
        try {
            out.writeUTF(name + " says: " + mess);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class Main  
{
   public static void main(String[] args) throws IOException {

       Main m = new Main();
       m.connect();
   }

   public void connect() throws IOException{
     //declare a scanner so we can write a message
       Scanner keyboard = new Scanner(System.in);


       // localhost ip
       String ip = "127.0.0.1";
       int port = 4444;
       Socket socket = null;

       System.out.print("Enter your name: ");
       String name = keyboard.nextLine();

       try {

       //connect
       socket = new Socket(ip, port);

       //initialize streams
       DataInputStream in = new DataInputStream(socket.getInputStream());
       DataOutputStream out = new DataOutputStream(socket.getOutputStream());

       //start a thread which will start listening for messages
       new ReceiveMessage(in).start();

       // send the name to the server!
       out.writeUTF(name);

       while (true){
           //Write messages :)
           String message = keyboard.nextLine();
           out.writeUTF(message);
       }

       }
       catch (IOException e){
           e.printStackTrace();
            if (!socket.isClosed()){socket.close();}
       }
   }

   class ReceiveMessage extends Thread{

       DataInputStream in;

       ReceiveMessage(DataInputStream in){
           this.in = in;
       }

       public void run(){
           String message;
           while (true){
               try {
                    message = in.readUTF();
                    System.out.println(message);

                } catch (IOException e) {
                e.printStackTrace();
                }

           }
       }

   }

}