I created websocket server using vert.x core 3.2.1. There are 2 paths "/read" and "/write" with which clients can work. In "/write"-path clinets write messages. If they coect the "/read"-path they must see this messages, which they have written in "/write". In order to accept my server I use SimpleWebsocketClient(in google chrome). So I want to do the next: for example 2 clients coect "/read" path. Nobody sent messages in "/write"-path. Client starts and displays "no messages.press end to exit",client remains opened. After some time other client enters "/write" path and sends a message and those clients which have already opened "/read" clients recieve this message. My code(server):
package com.webSocket;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.*;
import java.util.ArrayList;
public class serverTest {
static sockThread websocketThready;
static Buffer event;
static ArrayList<ServerWebSocket> websocketRepository=new ArrayList<>();
public static void main(String[] args) throws Exception {
serverTest servweb=new serverTest();
HttpServer server = Vertx.vertx().createHttpServer();
server.websocketHandler(new Handler<ServerWebSocket>() {
@Override
public void handle(ServerWebSocket webs) {
System.out.println("Client coected");
if (webs.path().equals("/write")) {
webs.handler(new Handler<Buffer>() {
@Override
public void handle(Buffer event) {
servweb.setEvent(event);
System.out.println("Received data: " + event.toString("ISO-8859-1"));
}
});
}
else if (webs.path().equals("/read")) {
websocketThready=new sockThread(webs);
Thread userSession=new Thread(websocketThready);
userSession.start();
System.out.println("thread started");
}
}
});
server.listen(8080, "localhost", res -> {
if (res.succeeded()) {
System.out.println("Server is now listening!");
} else {
System.out.println("Failed to bind!");
}
});
}
public Buffer getEvent() {
retu event;
}
public void setEvent(Buffer event) {
this.event = event;
}
}
I think,that it will be better to create separate class with thread. If a new client coect "/read" path, we transmit his websocket coection to thread and there I think it's necessary to open read stream for it and here is the main problem. I don't understand how to organize read-write stream in vert.x core. I tried to do such construction(but it doesn't works properly):
package com.webSocket;
import io.vertx.core.http.ServerWebSocket;
public class sockThread implements Ruable {
Thread socketThread=new Thread();
ServerWebSocket webs;
public sockThread(ServerWebSocket webs) {
this.webs = webs;
}
@Override
public void run() {
serverTest serverMessage=new serverTest();
webs.writeFinalTextFrame("no messages.press end to exit");
while(true){
if(serverMessage.getEvent()!=null)
webs.writeFinalTextFrame("echo: " + serverMessage.getEvent().toString("ISO-8859-1"));
}
}
}
Could anybody explain me how to organize write-read streams in websocket coection using vert.x?
