Hi All,
I am trying to use subprotocol in my websocket application having client in _javascript_ and server in java. But websocket connection is not establishes when trying to use subprotocol. Can you please help me understand
what I am missing out.
Client code:
const createConnection = () => {
console.log("initiating connection request",Date.now());
socket = new WebSocket(socketUrl,['chat','superchat']);
socket._onopen_ = (event) => {
debugger;
console.log('WebSocket connection established.',Date.now());
};
Server :
@OnWebSocketConnect
public void
onConnect(Session session) {
long
currentTimestamp = System.currentTimeMillis();
List<String> header = session.getUpgradeRequest().getSubProtocols();
logger.log(Level.ERROR,
CallerContext.DEFAULT_CONTEXT,
srcInfo,
"header is",
header);
String token =
null;
if (header !=
null) {
for
(String part : header) {
if
(part.contains("chat"))
{
token = part.trim();
// Do something with the token...
System.out.println("Access
token: " + token);
break;
}
}
}
//session.getUpgradeResponse().getHeaders().put("Sec-WebSocket-Protocol",header);
//System.out.println("Connect: " + session.getRemoteAddress());
String connectionId = UUID.randomUUID().toString();
this.setConnectionId(connectionId);
SessionCache.addToSessionMap(this);
// sending connectionId to client
this.session
= session;
//this.getSession()//.get
/* try
{
session.getRemote().sendString("Sec-WebSocket-Protocol: " + token);
}
catch (IOException e)
{
System.out.println(e);
}*/
try
{
JSONObject jsonObject = new
JSONObject();
jsonObject.put("connectionId",
connectionId);
// jsonObject.put("timestamp when reached server", currentTimestamp);
// jsonObject.put("Sec-WebSocket-Protocol:", "abc");
session.getRemote().sendString(jsonObject.toString());
}
catch
(IOException e) {
System.out.println("IO
Exception");
}
}
Thanks,
Poonam