简体   繁体   English

编写简单的控制台聊天程序

[英]Writing simple console chat program

So. 所以。 Im writing this simple chat program, and basically how it works now that the client and the server takes turn in writing a message. 我正在编写这个简单的聊天程序,以及客户端和服务器轮流编写消息后的工作原理。 Now i want the client and the server to be able to send multiple messages in a row instead of waiting for the counterpart. 现在,我希望客户端和服务器能够连续发送多个消息,而不是等待对方。

Any suggestions as to how i can send multiple messages, and also recieve multiple messages. 关于如何发送多条消息以及接收多条消息的任何建议。

I am new to network applications. 我是网络应用程序的新手。

Run method of Client: 客户端运行方法:

public void run(){
    while (true){
        System.out.println("Write message to server:");
        String besked = scanner.nextLine();
        oos.writeObject(besked);
        System.out.println("MEssage from server: " + (String)ois.readObject());
        oos.flush();
    }   
}        

And the run method of the Server: 和服务器的运行方法:

  public void run() {
      while(true){
              String s = (String)ois.readObject();
              System.out.println("Message from client: " +s);

              System.out.println("Write back:");
              String returbesked = scanner.nextLine();
              oos.writeObject(returbesked);
              oos.flush();
       }
  }

You can use two threads, (for each side of the connection) one reads data from the socket and other writes data to the socket. 您可以使用两个线程(对于连接的每一侧),一个线程从套接字读取数据,另一个线程将数据写入套接字。 When server accepts client connection, it creates two threads (in the code example they are called Reader and Writer threads). 当服务器接受客户端连接时,它将创建两个线程(在代码示例中,它们称为“ 读取器”和“ 写入器”线程)。 While writer thread continuously gets some data from a source and outputs the data to the socket,at the same time reader thread keeps reading data from the socket. 尽管编写器线程不断从源中获取一些数据并将其输出到套接字,但同时读取器线程仍从套接字中读取数据。 Input and output streams of a socket connection are independent of each other so they can be concurrently used. 套接字连接的输入和输出流彼此独立,因此可以同时使用。

In the below code I tried to realize the server side but it is pretty much the same for the client side as well: 在下面的代码中,我尝试实现服务器端,但对于客户端也几乎相同:

public class Test {

    public static void main(String[] args) {
        Server server = new Server();
        server.start(100);  // server port no 100
    }

}

class Server {

    /**
     * Thread that continuously reads data from socket.
     */
    private Thread reader;

    /**
     * Thread that continuously writes data to socket.
     */
    private Thread writer;

    /**
     * Start server
     * @param port
     * @throws IOException
     */
    void start(int port) throws IOException {
        ServerSocket srv = new ServerSocket(port);

        // Wait for client connection
        Socket clientSocket = srv.accept();

        // Client connected
        startReadingAndWritingData(clientSocket);
    }

    /**
     * Starts reader and writer threads.
     * 
     * @param socket
     *            client socket
     * @throws IOException
     */
    private void startReadingAndWritingData(Socket socket) throws IOException {
        ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(
                socket.getInputStream()));

        ObjectOutputStream oos = new ObjectOutputStream(
                new BufferedOutputStream(socket.getOutputStream()));

        ReaderThread reader = new ReaderThread(ois);
        WriterThread writer = new WriterThread(oos);
            reader.start();
            writer.start();

    }
}

class WriterThread extends Thread {

    private ObjectOutputStream oos;

    /**
     * Constructor.
     * 
     * @param oos
     */
    WriterThread(ObjectOutputStream oos) {
        super();
        this.oos = oos;
    }

    public void run() {
        while (true) {
            try {
                String output = getNextOutput();
                oos.writeObject(output);

                Thread.sleep(1000); // Wait before sending next String
            } catch (Exception e) {
                /*
                 * Socket IO or serialization error
                 */
                e.printStackTrace();
                break;
            }
        }
    }

    /**
     * Get output String from somewhere eg. file.
     * 
     * @return output
     */
    private String getNextOutput() {
        // TODO get output String from somewhere
    }

}

/**
 * Reader thread.
 * 
 */
class ReaderThread extends Thread {

    private ObjectInputStream ois;

    /**
     * Constructor.
     * 
     * @param ois
     */
    ReaderThread(ObjectInputStream ois) {
        super();
        this.ois = ois;
    }

    public void run() {
        while (true) {
            try {
                String input = (String) ois.readObject();
                handleInput(input);
            } catch (Exception e) {
                /*
                 * Socket IO or deserialization error
                 */
                e.printStackTrace();
                break;
            }
        }
    }

    /**
     * Handle received input String.
     * 
     * @param input
     */
    private void handleInput(String input) {
        // TODO handle input

    }

}

您将需要两个连接,一个在客户端写的连接,一个在服务器写的连接,或者您将需要使用非阻塞连接,即NIO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM