简体   繁体   中英

Multithreading this networking code in Java?

I'm trying to build a chat application on a CS framework, but I haven't quite figured out how to multithread the client code. I'd appreciate it if someone could point me in the right direction.

For starters, this bit of code just allows the client and server to communicate bidirectionally:

I won't paste the entire code, just the most important bits

Server

// main
public static void main (String[] args) {
    ChatServer cs = new ChatServer();
    cs.runServer();
}

// run ChatServer
public void runServer() {
    try {
        server = new ServerSocket (12345, 100);

        while (true) {
            try {
                waitForConnection();    // wait for connection
                getStreams();           // get IO streams
                processConnection();    // process connection
            } catch (EOFException eofException) {
                System.out.println("Server terminated connection");
            } finally {
                closeConnection();      // close connection
                ++counter;
            }
        }
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
}

// wait for connection, and display connection info
private void waitForConnection() throws IOException {
    System.out.println("Waiting for connection");
    connection = server.accept();
    System.out.println("Connection: " + counter + " received from: " + 
                    connection.getInetAddress().getHostName());
}

// get streams to send and receive data
private void getStreams() throws IOException {
    // set up output stream
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();                     // flush output buffer to send header information

    // set up input stream
    input = new ObjectInputStream(connection.getInputStream());

    System.out.println("Got I/O streams");
}

private void processConnection() throws IOException {
    String message = "Connection succesful";
    sendData(message);

    do {    // process messages sent from client
        try {
            message = (String) input.readObject();  // read new message
            System.out.println(message);        // display message
        } catch (ClassNotFoundException classNotFoundException) {
            System.out.println("Unkonwn object type received!");
        }
    } while (!message.equals("CLIENT>>> TERMINATE"));
}

Client

public static void main (String[] args) {
    Client application;

    // if no command line args
    if (args.length == 0) {
        application = new Client("127.0.0.1");
    } else {
        application = new Client(args[0]);
    }
}

// connect to server and process messages from server
public void runClient() {
    try {
        connectToServer();      // create Socket to connect to server
        getStreams();           // get input and output streams
        processConnection();    // process connection
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        closeConnection();
    }
}

// connect to server
private void connectToServer() throws IOException {
    displayMessage("Attempting connection\n");

    // create Socket to connect to server
    client = new Socket(InetAddress.getByName(chatServer), 12345);

    // dispaly connection information
    displayMessage("Connected to: " + client.getInetAddress().getHostName());
}

// get streams to send and receive data
private void getStreams() throws IOException {
    // set up output stream for objects
    output = new ObjectOutputStream(client.getOutputStream());
    output.flush();

    // set up input stream for objects
    input = new ObjectInputStream(client.getInputStream());

    displayMessage("\nGot I/O streams\n");
}

// process connection with server
private void processConnection() throws IOException {
    // enable enter field to send messages
    setTextFieldEditable(true);

    do {
        try {
            message = (String)input.readObject();
            displayMessage("\n" + message);
        } catch (ClassNotFoundException classNotFoundException) {
            displayMessage("\nUnknown object type received!");
        }
    } while (!message.equals("SERVER>>> TERMINATE"));
}

// close streams and socket
private void closeConnection() {
    displayMessage("\nClosing connection");
    setTextFieldEditable(false);

    try {
        output.close();
        input.close();
        client.close();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
}

My initial thoughts:

  1. The Client class should implement runnable, but I'm not sure what the run() method should wrap around...

  2. The Server class - I have a feeling the key is in the accept() line, but I'm not sure how to proceed...

I've only started learning multithreading in Java, but we're expected to build this multithreaded networking chat app lately, so I'm kinda lost as to how to proceed.

Would appreciate any guidance on this, thanks!

To keep this answer short, you need to basically,

  1. extract the methods getStreams() and processConnecion() inside a class that implements Runnable . These methods will be running in a Thread
  2. After waitForConnection() , construct your new Runnable Class, inject it your connection (or Streams) and start() it

Multithreading is very tough, and Java is absolutely no exception. Before you go too far in your application, make sure you fully understand how the Java Memory Model works and follow simple rules:

  • make variables as immutable as you can
  • avoid global or instance variable wherever you can
  • do not re-invent the wheel, use (abuse) the classes in the java.util.concurrent package
  • do not use synchronized all over the place 'just in case': your app will be inefficient and may just work better on a single thread

A an alternative to the Multithreading model, look at Actors using the Akka library

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