对于客户机-服务器应用程序,我创建以下服务器,该服务器使用连接器侦听端口8080。
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.websocket.server.WebSocketHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.server.Handler;
public class ProjectController {
public static void main(String[] args) throws Exception {
Server server = new Server();
ServerConnector primary=new ServerConnector(server);
primary.setPort(8080);
primary.setName("Primary");
server.addConnector(primary);
ServerConnector secondary=new ServerConnector(server);
secondary.setPort(4321);
secondary.setName("Secondary");
server.addConnector(secondary);
WebSocketHandler primaryHandler = new WebSocketHandler() {
@Override
public void configure(WebSocketServletFactory factory) {
factory.register(PrimarySocketHandler.class);
}
};
server.setHandler(primaryHandler);
server.start();
server.join();
}
}
此连接器将primarysockethandler作为带有@websocket注解的上下文:
import java.io.IOException;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
@WebSocket
public class PrimarySocketHandler {
DataRetriever dr;
String reply;
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("Close: statusCode=" + statusCode + ", reason=" + reason);
}
@OnWebSocketError
public void onError(Throwable t) {
System.out.println("Error: " + t.getMessage());
}
@OnWebSocketConnect
public void onConnect(Session session) {
System.out.println("Connected");
}
@OnWebSocketMessage
public void onMessage(Session session, String message) {
dr=new DataRetriever();
try {
reply=dr.retrieveQuotes(message);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
session.getRemote().sendString(reply);
} catch (IOException e) {
e.printStackTrace();
}
}
}
我想用另一个连接器在另一个端口上打开客户端的并行连接。我可以创建一个新的websocket处理程序(类)并将其Map到新的连接器吗?如果是,怎么做?
基本上,我需要的是服务器的两个“示例”来同时侦听不同的端口,因此我需要两个处理程序来处理来自每个端口的传入数据。
我也对不同的方法持开放态度。
暂无答案!
目前还没有任何答案,快来回答吧!