/miniServer

Simplified Java TCP server. Can be used for multiplayer purposes, like games

Primary LanguageJava

miniServer

Simplified Java TCP server. Can be used for multiplayer purposes in games

Setup guide

You can copy folders and files from the src folder directory directly inside your project. If you don't want the examples, you can delete the example subfolder.

How to use it

First of all don't forget to import it

import com.therolf.miniServer.Client;
import com.therolf.miniServer.Message;
import com.therolf.miniServer.Server;

Client side

  1. You need to connect to your server so what you do is that you create a client:
    String ip = "127.0.0.1"; // match with server
    int port = 3000; // match with server
    Client client = new Client(ip, port);
  2. What you need next is a username to be recognized ans send messages to everyone :
    String login = "John Wick";
    client.send(login);
  3. Then when you are authed, the isAuthed() method will return true.
  4. You can then finally send strings with the send(String s) method.
  5. Alternatively, you can listen to incoming messages with the isReady and read messages:
    // receive messages
    while(client.isRunning()) {
        if(client.isReady()) {
            Message m = client.read();
            System.out.println(m.getPseudo() + ": " + m.getMessage());
        }
    }

(Don't forget to wrap it with try catch for error handling)
Go checkout ClientExample.java for a real example.

Server side

The server side is also simple!

  1. You create a server object:
    String port = 3000; // match with client
    String serverName = "ServerExample";
    String ip = "127.0.0.1"; // match with server
    Server miniServer = new Server(port);
    Server miniServer = new Server(port, serverName);
    Server miniServer = new Server(port, serverName, ip);
  2. You listen for messages and respond to them if you want:
    miniServer.setMessageListener((fromPseudo, message) -> {
        switch (message) {
            case "hello":
                miniServer.sendToEveryoneElse(fromPseudo, fromPseudo + " says hello");
                break;
            case "list":
                miniServer.sendFromTo(miniServer.getServerName(), fromPseudo, miniServer.getAllPseudos());
                break;
            case "ping":
                miniServer.sendFromTo(miniServer.getServerName(), fromPseudo, "pong");
                break;
            default:
                miniServer.sendToEveryone(fromPseudo, message);
                break;
        }
    });
  3. You run it and it does its life on its own:
    miniServer.run();
  4. Go checkout ServerExample.java for a real example.