简体   繁体   中英

JAVA Wrapping Socket as a Singleton class in a multiscreen Swing app

I am writing a chat application in Java swing which has a custom protocol and server backend using sockets. I am in the process of making the ClientSide connection handler. Here is my code up to this point:

package Client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

import Common.Message;

public class ConnectionHandler {
    Socket socket;
    DataInputStream input;
    DataOutputStream output;

    public ConnectionHandler() throws UnknownHostException, IOException {
        socket = new Socket(Client.HOST_INET,Client.PORT);
        input = new DataInputStream(socket.getInputStream());
        output = new DataOutputStream(socket.getOutputStream());
    }

    public void sendMessage(Message message) throws IOException {
        output.writeUTF(Message.disasseble(message));
    }

    public Message getMessage() throws IOException {
        String message;
        message = input.readUTF();
        return Message.assemble(message);   
    }

    public void closeConnection() {

    }

    private void reconect(){

    }
}

The app is composed of a CardLauut holding the Login, Registration and and Chat JPanels. Each JPanel needs the connection and the connection should be maintained as long as the app is functioning. Login screen sends Login message/answer the same with Registration and of course the Chat screen.

QUESTION Should I use a singleton design pattern for the connectionHanler? And would the referece also work if it was on a separate thread like a connection thread with a que? (I know that I need to ping the server every now and then or connection can be lost so I need to reconect and let the UI know)

It makes sense to keep ConnectionHandler singleton for the following reasons:

  • You can manage connection state centrally, inside the ConnectionHandler instance. For eg, don't send a chat message if user isn't logged in.
  • Allows messages to be sent in sequence. If you don't use Singleton pattern, it is theoretically possible that messages can be sent out of order in a multi-threaded application.
  • Decrease load on server, because it only has one socket connection per client.

Holding the connection in a singleton has one additional advantage: you will very likely want to run all of your network communication in dedicated Thread. A singleton can greatly help there.

Also all Connection related properties (logged in?, transport encryption, ...) can be handled on a „per connection“ base.

Handling out-of-band communication („log out“ or notifications while the Socket is busy) should be considered beforehand.

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