java 一个简单的客户端/服务器聊天程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15188741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:46:09  来源:igfitidea点击:

a simple client/server chat program

javanetbeans

提问by Renaud is Not Bill Gates

I'm trying to create a simple chat program using java, which contains to forms, a client form and a server form, the client form contains a TextField and a Button (send button), and the server form contains a TextArea.

我正在尝试使用 java 创建一个简单的聊天程序,其中包含表单、客户端表单和服务器表单,客户端表单包含一个 TextField 和一个按钮(发送按钮),服务器表单包含一个 TextArea。

When I click on the send button it should send the wrote text in the TextField to the TextArea in the server form.

当我单击发送按钮时,它应该将 TextField 中写入的文本发送到服务器表单中的 TextArea。

for the first time it works but when I click on the button in the second time it won't work.

第一次它起作用了,但是当我第二次单击该按钮时它不起作用。

this is the code I used in the Server Form :

这是我在服务器表单中使用的代码:

public class Server extends javax.swing.JFrame implements Runnable {

    private Thread th;

    public Server() {
        initComponents();
        th = new Thread(this);
        th.start();
    }

    // The main method was here

    @Override
    public void run() {

        // Etablir la connexion
        try {
            ServerSocket ecoute;
            ecoute = new ServerSocket(1111);
            Socket service = null;
            System.out.println("Serveur en attente d'un client !");
            while (true) {

                service = ecoute.accept();
                System.out.println("Client connécté !");
                DataInputStream is = new DataInputStream(service.getInputStream());
                jTextArea1.setText("Client dit : "+ is.readUTF().toUpperCase());
                service.close();
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
    }
}

and this is the code of the client form:

这是客户端表单的代码:

    public class Client extends javax.swing.JFrame {

    DataOutputStream os;

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            os.writeUTF(jTextField1.getText());
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE,null, ex);
        }
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Client c = new Client();
                c.setVisible(true);

                try {
                    Socket s = new Socket("localhost", 1111);
                    c.os = new DataOutputStream(s.getOutputStream());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

}

采纳答案by sissi_luaty

Your problem is in the server's code: to receive various messages from various clients at the server's side, for each accept, i.e. each client, you have to create one thread to process its requests, because you are using TCP connections. (- you were only processing one request per accept, and then closing the connection).

您的问题出在服务器的代码中:要从服务器端的各个客户端接收各种消息,对于每个接受,即每个客户端,您必须创建一个线程来处理其请求,因为您使用的是 TCP 连接。( - 您每次接受仅处理一个请求,然后关闭连接)。

I cleaned the parts unrelated to sockets of your code, (i.e. some incomplete parts related to the GUI in the client), so I present a different version that works well for many simultaneous clients' connections, and you can see all the messages arriving to the server, and not only the 1st message.

我清理了与您的代码的套接字无关的部分(即与客户端中的 GUI 相关的一些不完整的部分),因此我提供了一个适用于许多并发客户端连接的不同版本,您可以看到所有到达的消息服务器,而不仅仅是第一条消息。

servers' code:

服务器代码:

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


public class Server {

    public static void run() {
        try
        {
            ServerSocket ecoute;
            ecoute = new ServerSocket(1111);
            Socket service = null;
            System.out.println("serveur en attente d'un client!");
            while(true)
            {
                service = ecoute.accept();
                System.out.println("client connécté!");
//              ##call a new thread
                WorkerThread wt = new WorkerThread(service);
                wt.start();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        run();
    }
}


class WorkerThread extends Thread {
    Socket service;
    WorkerThread(Socket service) {
        this.service = service;
    }

    public void run() {
    boolean flag=true;    //you can change this flag's condition, to test if the client disconects
    try
    {
        while (flag){
            DataInputStream is = new DataInputStream(service.getInputStream());
            System.out.println("client dit: " + is.readUTF().toUpperCase());
        }
        service.close();
    }
    catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

clients' code:

客户代码:

import java.io.*;
import java.io.*;
import java.net.*;
import java.util.logging.*;


public class Client {

DataOutputStream os;

public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
               Client c = new Client();
        try {
            Socket s = new Socket("localhost", 1111);
            c.os = new DataOutputStream(s.getOutputStream());
            while (true){
                String str = Input.read_string();
                c.os.writeUTF(str);
            }
        } catch ( IOException e) {
            // TODO auto-generated catch block
            e.printStackTrace();
        }
            }
        });
    }
}

public class Input{
    public static String read_string(){
        String read="";
        try{
            read = new BufferedReader(new InputStreamReader(System.in), 1).readLine();
        }catch (IOException ex){
            System.out.println("error reading from the input stream!");
        }
        return read;
    }
}

After that, you need, as you probably know, to send all those messages that arrive to the server to all the clients in the chat room.

之后,您可能知道,您需要将所有到达服务器的消息发送给聊天室中的所有客户端。

回答by ddmps

In your while(true)section of the Servercode - you are closing the socket after you read it once, while at the client you do not reopen a Socket(and a new InputStream). What I suggest is that you have another loop in your while(true)section that will keep on reading and display new data until the EOF is reached.

在您while(true)Server代码部分- 您在阅读一次后关闭套接字,而在客户端您不会重新打开 a Socket(和一个 new InputStream)。我建议您在您的while(true)部分中有另一个循环,它将继续读取和显示新数据,直到达到 EOF。