feat: Started basic implementation of socket comm
This commit is contained in:
@@ -1,7 +1,18 @@
|
||||
package cz.jzitnik.server;
|
||||
|
||||
public class Main {
|
||||
static void main() {
|
||||
import jakarta.websocket.DeploymentException;
|
||||
import org.glassfish.tyrus.server.Server;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
static void main() throws DeploymentException {
|
||||
Map<String, Object> properties = new HashMap<>();
|
||||
Server server = new Server("localhost", 8025, "/", properties, WebSocket.class);
|
||||
|
||||
server.start();
|
||||
new Scanner(System.in).nextLine();
|
||||
}
|
||||
}
|
||||
|
||||
53
server/src/main/java/cz/jzitnik/server/WebSocket.java
Normal file
53
server/src/main/java/cz/jzitnik/server/WebSocket.java
Normal file
@@ -0,0 +1,53 @@
|
||||
package cz.jzitnik.server;
|
||||
|
||||
import cz.jzitnik.common.socket.SocketMessage;
|
||||
import cz.jzitnik.common.socket.messages.Test;
|
||||
import jakarta.websocket.*;
|
||||
import jakarta.websocket.server.ServerEndpoint;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
@Slf4j
|
||||
@ServerEndpoint("/ws")
|
||||
public class WebSocket {
|
||||
|
||||
@OnOpen
|
||||
public void onOpen(Session session) {
|
||||
log.debug("Client connected: " + session.getId());
|
||||
|
||||
try {
|
||||
SocketMessage response = new Test();
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(baos);
|
||||
oos.writeObject(response);
|
||||
oos.flush();
|
||||
session.getBasicRemote().sendBinary(java.nio.ByteBuffer.wrap(baos.toByteArray()));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// Receive binary data from client
|
||||
@OnMessage
|
||||
public void onMessage(byte[] bytes, Session session) {
|
||||
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
|
||||
ObjectInputStream ois = new ObjectInputStream(bais)) {
|
||||
|
||||
SocketMessage socketMessage = (SocketMessage) ois.readObject();
|
||||
System.out.println("Received: " + socketMessage);
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@OnClose
|
||||
public void onClose(Session session, CloseReason reason) {
|
||||
System.out.println("Connection closed: " + reason);
|
||||
}
|
||||
|
||||
@OnError
|
||||
public void onError(Session session, Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user