简体   繁体   中英

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。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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