• Stars
    star
    118
  • Rank 299,923 (Top 6 %)
  • Language
    Java
  • License
    MIT License
  • Created about 10 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Threaded Java socket server and client

Socket

Gitter chat

Threaded Java socket server and client

Example

Create a server at port 5556 with a MessageHandler, which is the EchoHandler in this example.

SocketServer server = new SocketServer(5556, new EchoHandler());

Create a client connecting to localhost's port 5556.

SocketClient client = new SocketClient(InetAddress.getLocalHost(), 5556);

Send a message from the client.

client.println("Hello!");

Print out the message from the server. The function SocketClient.readLine() blocks.

System.out.println(client.readLine());

The EchoHandler implements the MessageHandler interface and overrides the abstract method onReceive(). The argument connection enables you to send a string back to the client.

public class EchoHandler implements MessageHandler {
    @Override
    public void onReceive(Connection connection, String message) {
        connection.send(message);
    }
}

Features

SocketServer is threaded. It creates a thread for accepting connections and creates a new thread each time a new client is connected. SocketClient is not threaded and the function readLine() blocks.