我在Java中有一个Websocket客户端,可以连接到服务器。它每10秒钟从服务器接收一次心跳消息(直到30秒钟消失,然后由于某种原因断开连接,但现在暂时将其忽略)。但是,如果在最初的30秒钟内发送消息,我会立即收到通知,通知该连接已关闭,原因码为1000。
我在python中有一个类似的客户端,可以正常工作,并连接到相同的服务器位置。我实际上正在尝试在Java中实现相同的功能,但无法使其正常工作。
websocket客户端代码段。我必须重写beforeRequest才能传递Cookie:
ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create()
.configurator(new ClientEndpointConfig.Configurator() {
@Override
public void beforeRequest(Map<String, java.util.List<String>> headers) {
super.beforeRequest(headers);
List<String> cookieList = headers.get("Cookie");
if (null == cookieList) {
cookieList = new ArrayList<String>();
}
cookieList.add("User-Session-Token=\"" + SESSION_COOKIE + "\""); // set your cookie value here
headers.put("Cookie", cookieList);
System.out.println(cookieList.size() + ": " + cookieList.get(0));
}
}).build();
String uri = "wss://live.someurl.com/sockjs/997/" + SESSION_ID + "/websocket";
Endpoint myEndpoint = new MyClientEndpoint();
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
Session session = container.connectToServer(myEndpoint, clientEndpointConfig, URI.create(uri));
String name = "{\"path\":\"blah\"}";
System.out.println("Sending message to endpoint: " + name);
Future<Void> abc = session.getAsyncRemote().sendText(name);
终点:
@ClientEndpoint
public class MyClientEndpoint extends Endpoint{
@Override
public void onOpen(Session session, EndpointConfig arg1) {
session.addMessageHandler(new MessageHandler.Whole<String>() {
@Override
public void onMessage(String arg0) {
// TODO Auto-generated method stub
System.out.println("Message received: " + arg0);
}
});
}
}
如果有帮助,起作用的python代码的内脏看起来像这样:
class MyWebsocketClass:
def __await__(self):
log("Initializing Classes......")
return self._async_init().__await__()
async def _async_init(self):
#create socket conn
self._conn = connect(f'wss://live.someurl.com/sockjs/997/{SESSION_ID}/websocket',
extra_headers=[("Cookie", SESSION_COOKIE)])
log("Connected to websocket......")
self.websocket = await self._conn.__aenter__() # not sure what this is?
return self
async def close(self):
await self._conn.__aexit__(*sys.exc_info())
async def send(self, message):
await self.websocket.send(json.dumps(message))
async def receive(self):
return await self.websocket.recv()