开发者

Help with proper design for generic Socket Server

I've created a generic 'SocketServer' class in java which takes the following arguments: String address, int port, Class socketProtocol, String encryptionType, int backlogSize

Basically, I want other developers to be able to instance this class in their projects and set some simple options for encryption, backlog, address, port.. at which point they have to design the protocol. SocketProtocol is an interface which enables sendMessage and receiveMessage (along with a few others).

At this point, the user of the class should just implement SocketProtocol and pass the class (i.e. MySocketProto.class) to the 开发者_运维知识库 SocketServer instance, which will in turn instance a copy of the protocol for each incoming connection via .newInstance();

Does this make sense? Is there an easier way to establish this type functionality? I don't like the idea of passing the class type to the server, it just seems odd.

Thanks all, Chris


I would use the Factory pattern in this situation. The linked Wikipedia example is a bit verbose, but it can be really simple:

public interface ISocketProtocolFactory {
    ISocketProtocol buildProtocol();
}

Your SocketServer constructor would then take an instance of something implementing ISocketProtocolFactory, and ask it for new ISocketProtocols as it goes.

This will give your users a lot more flexibility in constructing the ISocketProtocol instances, take care of the 'nastiness' of having a class parameter.


I would assume that each port would have it's own protocol. With that in mind you would specify it for the port.

The way I had done it in the past is to have the implementors pass in a class that inherits from:

public Interface ProtocolInterface
{
   public void serve(InputStream in, OutputStream out) throws IOException
...

where the InputStream and OutputStream are the input and outputs to the Socket

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜