Java 简单服务器/客户端控制台聊天应用程序

标签 java console client

我想创建一个简单的服务器客户端应用程序,但我认为 IO 流有问题。没有 GUI,因此聊天将通过控制台进行(您可以打开 2 个 Eclipse 来测试它或您使用的任何 IDE)。

这是我的服务器代码:

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {
    ServerSocket serverSocket;
    Socket connection; // connection-to-client
    ObjectOutputStream output;
    ObjectInputStream input;

    public void run() {
        try {
            serverSocket = new ServerSocket(6000, 100);
        } catch (IOException e) {
            System.err.println("Invalid port number");
        }
        while (true) {
            try {
                waitForConnection();
                getIOStreams();
                processConnection();
            } finally {
                closeConnection();
            }
        }
    }

    public void closeConnection() {
        try {
            input.close();
            output.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void waitForConnection() {
        System.out.println("Server is ready to accept conenctions");
        try {
            connection = serverSocket.accept(); // code will stop here until a
                                                // connection occurs
            System.out.println("Conenction established with the client");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getIOStreams() {
        try {
            output = new ObjectOutputStream(connection.getOutputStream());
            output.flush(); // send header information to the client, which
                            // contains info required to create the input stream
                            // object
            input = new ObjectInputStream(connection.getInputStream());
            System.out.println("Server established I/O streams");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void processConnection() {
        sendData("Connection established with the server");
        String inputMessage = "";
        new Runnable() {
            Scanner sc = new Scanner(System.in);

            public void run() {
                while (true) {
                    sendData(sc.nextLine());
                }
            }
        };
        do {

            try {
                inputMessage = (String) input.readObject();
                System.out.println(inputMessage);
            } catch (ClassNotFoundException e) {
                System.err.println("Object of an unknown type was recieved");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } while (inputMessage.equals("QUIT"));
    }

    public void sendData(String s) {
        try {
            output.writeObject(s);
            output.flush();
            System.out.println("Server: " + s);
        } catch (IOException e) {
            System.err.println("Error writting the message");
        }
    }
}

这是我的客户端代码

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
    ServerSocket serverSocket;
    Socket clientSocket;
    ObjectOutputStream output;
    ObjectInputStream input;
    String serverAddress = "127.0.0.1";

    public void run() {
        connect2Server();
        getIOStreams();
        processConnection();
        closeConnection();
    }

    public void connect2Server() {
        System.out.println("Trying to connect to the server");
        try {
            clientSocket = new Socket(serverAddress, 6000);
        } catch (UnknownHostException e) {
            System.err.println("Server unavailable");
            System.exit(1);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void getIOStreams() {
        try {
            output = new ObjectOutputStream(clientSocket.getOutputStream());
            output.flush();
            input = new ObjectInputStream(clientSocket.getInputStream());
            System.out.println("Client established I/O Stream");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void processConnection() {
        sendData("Connection established with the client");
        String inputMessage = "";
        new Runnable() {
            Scanner sc = new Scanner(System.in);

            public void run() {
                String outputMessage = "";
                do {
                    outputMessage = sc.nextLine();
                    sendData("Client: " + outputMessage);
                } while (outputMessage.equals("QUIT"));
            }
        };
        while (true) {

            try {
                inputMessage = (String) input.readObject();
                System.out.println(inputMessage);
            } catch (ClassNotFoundException e) {
                System.err.println("Object of an unknown type was recieved");
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }

    public void sendData(String s) {
        try {
            output.writeObject(s);
            output.flush();
            System.out.println("Client: " + s);
        } catch (IOException e) {
            System.err.println("Error writting the message");
        }
    }

    public void closeConnection() {
        try {
            output.close();
            input.close();
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

要运行服务器或客户端,只需在主客户端/服务器中编写。运行(); 请告诉我我的错误是什么以及如何解决:)

最佳答案

几点:

1) 输入循环结束条件不正确:

while (inputMessage.equals("QUIT")); // Server#processConnection 

while (outputMessage.equals("QUIT")) // Client#processConnection 

这些应该被否定(“!”)。

2) 你应该开始你的 System.in 阅读线程:

new Thread() { // instead of `Runnable`
   ...
}.start();

3) 你应该打破服务器上的一些异常监听循环,比如 EOFException 这意味着客户端已断开连接。

关于Java 简单服务器/客户端控制台聊天应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7724159/

相关文章:

java - 需要 Java 正则表达式的线索

python - 在单线程 Python 脚本中有一个控制台

objective-c - 如何将控制台输出到 uitextview?访问控制台日志

windows - Debian Samba - protected 文件夹和公共(public)文件夹的混合 - Win 7 客户端

java - 在java中实例化泛型类型

java - 如何在 jar 文件中使用 SQLite 数据库?

java - 在 Spring 中发布多个表单记录

c - 为什么多字节字符到 char32_t 的转换使用 UTF-8 作为多字节编码而不是特定于语言环境的编码?

java - 如何使用套接字将数据从服务器发送到多个客户端?

.net - 使用 New Relic 监控独立 .NET 桌面应用程序的性能