java - 陷入多客户端聊天应用程序困境

标签 java multithreading swing sockets

我正在尝试制作一个多客户端聊天应用程序,其中聊天是在客户端窗口中实现的。我已经尝试过相同的服务器和客户端代码。我有两个问题: 答:我相信代码应该可以工作,但是服务器到客户端的连接很好,但信息不会在客户端之间传输。 B. 我需要一种方法来实现两个以上客户端的私有(private)一对一聊天,我使用了一个类来存储为每个建立的连接返回的 Socket 对象的信息,但我不知道如何实现它。

服务器代码是:

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

class ClientInfo {

Socket socket;
String name;

public ClientInfo(Socket socket, String name) {
    this.socket = socket;
    this.name = name;
}
}

public class server {

private ObjectInputStream input[] = null;
private ObjectOutputStream output[] = null;
private String value = null;
private static ServerSocket server;
private Socket connection = null;

private static int i = -1;

public static void main(String args[]) {
    try {
        server = new ServerSocket(1500, 100);
        while (true) {
            System.out.println("Waiting for connection from client");
            Socket connection = server.accept();
            i++;
            System.out.println("Connection received from " + (i + 1) + " source(s)");
            //System.out.println(i);

            new ClientInfo(connection, "Client no:" + (i + 1));
            innerChat inc = new server().new innerChat(connection);

        }
    } catch (Exception e) {
        System.out.println("Error in public static void main! >>>" + e);
    }
}// end of main!!!

class innerChat implements Runnable {

    private Socket connection = null;

    public innerChat(Socket connection) {
        this.connection = connection;
        Thread t;
        t = new Thread(this);
        t.start();
    }

    public void run() {
        try {
            output[i] = new ObjectOutputStream(connection.getOutputStream());
            output[i].flush();
            input[i] = new ObjectInputStream(connection.getInputStream());
        } catch (Exception e) {
        }
    }
}
}

客户端代码

import java.net.*;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.*;
import java.awt.event.*;

 public class ChatappClient {

private static int port = 1500;
JFrame window = new JFrame("Chat");
JButton sendBox = new JButton("Send");
JTextField inputMsg = new JTextField(35);
JTextArea outputMsg = new JTextArea(10, 35);
private ObjectInputStream input;
private ObjectOutputStream output;

public static void main(String[] args) throws Exception {
    ChatappClient c = new ChatappClient();
    c.window.setVisible(true);
    c.window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    c.run();
}

    public ChatappClient() {

    inputMsg.setSize(40, 20);
    sendBox.setSize(5, 10);
    outputMsg.setSize(35, 50);
    inputMsg.setEditable(true);
    outputMsg.setEditable(false);
    window.getContentPane().add(inputMsg, "South");
    window.getContentPane().add(outputMsg, "East");
    window.getContentPane().add(sendBox, "West");
    window.pack();
    sendBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                output.writeObject(inputMsg.getText());
                outputMsg.append("\n" + "Client>>>" + inputMsg.getText());
                output.flush();
            } catch (IOException ie) {
                outputMsg.append("Error encountered! " + ie);
            }
            inputMsg.setText("");
        }
    });
    inputMsg.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                output.writeObject(inputMsg.getText());
                outputMsg.append("\n" + "Client>>>" + inputMsg.getText());
                output.flush();
            } catch (IOException ie) {
                outputMsg.append("Error encountered! " + ie);
            }
            inputMsg.setText("");
        }
    });
}

private void run() throws IOException {
    Socket clientSocket = new Socket("127.0.0.1", port);
    output = new ObjectOutputStream(clientSocket.getOutputStream());
    output.flush();
    input = new ObjectInputStream(clientSocket.getInputStream());
    outputMsg.append("I/O Success");
    String value = null;
    while (true) {
        try {
            value = (String) input.readObject();
        } catch (Exception e) {
        }
        outputMsg.append(value + "\n");
    }
}
}

最佳答案

您的代码看起来还可以改进很多。例如,您的 main 方法中不应包含任何代码。它应该启动您的 Server 类,仅此而已(请注意,根据 Java 标准,类名应以大写字母开头,我强烈建议您遵循该标准)。

I'm trying to make a MultiClient Chat Application in which a Server does nothing but listen and create connections.

服务器要做的事情还不止这些。它需要创建客户端,需要维护一个集合,例如客户端的 ArrayList,例如 ArrayList<ChatappClient>否则你期望服务器如何将两个客户端连接在一起?

我认为在开始编写代码之前,您需要更深入地思考该程序的结构和连接。

关于java - 陷入多客户端聊天应用程序困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17607218/

相关文章:

java - 在android中创建菜单时出错

java - 当我放置 WHERE 子句时,UPDATE 命令出现问题,它在 objectDB 中崩溃

c# - 将对象的引用传递给新线程

java - 如何更改 JTabbedPane 中选项卡的顺序

Java 图形错误 : Static/Nonstatic mishap

java - 热图 - 生成简单 'HeatPoint' Google Maps Android

java - Retrofit:如何发送带有常量字段的 POST 请求?

java - Thread.sleep() 不工作。被跳过的操作

c++ - SFML 中的线程创建错误

java - GridLayout 以及行数和列数