πŸ“œ ⬆️ ⬇️

Java socket framework

Good day to all. I develop online 3d game, java platform was chosen. For 3d, the jmonkeyengine engine was chosen. And as the server side, I decided to write a simple p2p framework, MVC with the implementation of views on the client.


Updated blog with examples and documentation:
java-framework-jsocket.blogspot.com

Where it may come in handy:
')
1. Server for mobile services.
2. Any multi-user applications where you need p2p.
3. Online games.
4. Torrent if desired.

Diagram:
image

Principle of operation:

1. The client sends to the server a message that lists the variables and what task to call.
2. The message hits the inbox queue.
3. The router starts the desired task with these variables.
4. In the task we send the answer to the user.

Additional features:

1. Configure the client and server ports.
2. Database models.
3. Validation of incoming messages.
4. User rights.
5. Modules.
6. Session mechanism.
7. Teams.
8. Change protocol tcp / udp.

Instructions, examples and documentation

β†’ http://jsockframework.blogspot.com/
β†’ https://github.com/nnpa/jsock/
β†’ youtube
β†’ jsock.doc

Example of sending and receiving messages

Customer:

//client /* * jsock framework https://github.com/nnpa/jsock open source * Each line should be prefixed with * */ package jsock.tests; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.Iterator; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import conf.JConfig; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** * * @author padaboo IB Aleksandrov jetananas@yandex.ru */ public class JClientTCPTest { public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException{ JClientTCPTest tcpTest = new JClientTCPTest(); tcpTest.test(); } public void test(){ Sender sender = new Sender(); sender.start(); Receiver receiver = new Receiver(); receiver.start(); } class Sender extends Thread{ @Override public void run(){ try { InetAddress host = InetAddress.getLocalHost(); Socket socket = null; String message; for(int i=1; i<10;i++){ message = "{\"task\":\"JTestTask\",\"message\":\"test"+i+"\"}"; socket = new Socket(host.getHostName(), JConfig.server_port); //InputStream inStream = socket.getInputStream(); PrintWriter socketOut; socketOut = new PrintWriter(socket.getOutputStream(), true); socketOut.println(message); socket.close(); System.out.println("Send: "+i); Thread.sleep(100); } } catch ( IOException | InterruptedException ex) { Logger.getLogger(JClientTCPTest.class.getName()).log(Level.SEVERE, null, ex); } } } class Receiver extends Thread{ JSONObject jsonObj; JSONParser parser; @Override public void run(){ try { ServerSocket serverSocket = new ServerSocket(JConfig.client_port); String data = ""; while(true){ data = ""; Socket socket = serverSocket.accept(); InputStream inStream = socket.getInputStream(); Scanner scanner = new Scanner(inStream); while(scanner.hasNextLine()){ data += scanner.nextLine(); } System.out.println(data); } } catch (IOException ex) { Logger.getLogger(JClientTCPTest.class.getName()).log(Level.SEVERE, null, ex); } } } } 

Server:

 package tasks; import jsock.message.JInMessages; import jsock.message.JOutMessages; import jsock.task.JClientTask; import models.Users; /** * * @author padaboo IB Aleksandrov jetananas@yandex.ru */ public class JTestTask extends JClientTask{ public JTestTask(JInMessages message) { super(message); } @Override public String[][] rules(){ String[][] rules = { {"require","message"} }; return rules; } @Override public String rights() { //String rigths = "user,admin"; String rigths = "guest"; return rigths; } @Override public void action(){ String message = this.message.json.get("message").toString(); System.out.println(message); String outString = "{\"message\":\"Test\"}"; JOutMessages outMessage = new JOutMessages(this.message.ip,outString); outMessage.insert(); } } 

1. The client sends to the json server a string with the name of the task being called.
2. The task retrieves the variables from the message and sends the response.

Task

The task must be created in the tasks folder and inherited from JClientTask. In the constructor, the JInMessages class with the incoming message must be passed. The methods rules, rights, action must be implemented. The rules describe the validation rules for variables; you can write your own validation rules. In rights, listing the rights of users who have the right to trigger an action.
in action the main code.

Retrieving variables

  String message = this.message.json.get("message").toString(); 

Response and queuing line

 String outString = "{\"message\":\"Test\"}"; JOutMessages outMessage = new JOutMessages(this.message.ip,outString); outMessage.insert(); 

Instead of ip, you can put any ip that listens to the socket and waits for the json string.

Models

After installing the framework, according to the instructions there will be 2 tables in the database: Users, Session. Examples of use are in folders with tasks.

All models must be created in the models folder, inherited from DBQuery in which the connection to the database and the main methods are implemented. In the model class the logic of interaction with the database should be implemented.

User rights

1. Rights must be described in tasks in the rights method: guest, user, admin. Unauthorized user has guest rights. The registered user is assigned user, these values ​​are stored in the database in the rights table.

Example: authorization by token, model, right

Getting a token

 @Override public void action(){ String email = this.message.json.get("email").toString(); String password = this.message.json.get("password").toString(); Users users = new Users(); boolean isAuth = users.authorization(email,password); String outString; if(isAuth){ String token = users.getToken(); int userId = users.id; String ip = this.message.ip; //System.out.println(insertQuery); Session session = new Session(); session.setToken(userId, token,ip); outString = "{\"token\":\"" + token +"\"}"; }else{ outString = "{\"error\":\"Incorrect login or password \"}"; } JOutMessages outMessage = new JOutMessages(this.message.ip,outString); outMessage.insert(); } 

1. In the right we specify the expected variables: email, password.
2. Create the Users model, call the authorization method.
3. Create a session model - we get a token.
4. We send the answer.
5. Save the token on the client.

An example of checking rights and sending messages to a specific ip

 @Override public void action(){ /** * get ip from session and send to open socket **/ System.out.println("user_id: " + webUser.id + " email: " + webUser.email + " rights: "+ webUser.rights); Session session = new Session(); session.findByUserID(12); String ip = session.ip; //all users //session connection String outString = "{\"ip_message\":\"send to user by session id\"}"; JOutMessages outMessage = new JOutMessages(ip,outString); outMessage.insert(); } 

1. In the rights we specify user.
2. In the expected variables token

After calling a task with a token and non-guest rights. The user is searched in the database in the Session table, the user model is created by user_id - which is available in the task in the webUser variable.

You can send messages to all clients by user_id in Session or by connection in the JConnections class.

An example of registration can be viewed in the tasks class. JRegistrationTask. All tests are in the folder / tests /. More detailed examples can be found on the links at the beginning of the message.

UPD: Framework updated bugs fixed, new features added
UPD: I started writing a tutorial: jsock-framework-tutorial.blogspot.com/2019/02/jsock-framework.html

Source: https://habr.com/ru/post/318782/


All Articles