使用Java EE中的特定IP发送WebSocket请求(Send WebSocket request using specific IP in Java EE)

我使用Tyrus进行连接。 这是代码:

public void connect(String IP) { WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer(); ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() { public void beforeRequest(Map<String, List<String>> headers) { List<String> originValue = new ArrayList<>(); originValue.add("http://example.com"); headers.put("Origin", originValue); } }; ClientEndpointConfig clientConfig = ClientEndpointConfig.Builder.create() .configurator(configurator) .build(); try { webSocketContainer.connectToServer(this, clientConfig, new URI(IP)); } catch (Exception e) { ... } }

我的电脑有几个IP地址。 我想从选定的IP发送WebSocket请求 - 我想将WebSocket绑定到特定的本地IP。 有可能吗? 我应该使用其他图书馆吗?

编辑:我发现netty - 它允许手动设置本地IP地址。

I used Tyrus to make the connection. Here is the code:

public void connect(String IP) { WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer(); ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() { public void beforeRequest(Map<String, List<String>> headers) { List<String> originValue = new ArrayList<>(); originValue.add("http://example.com"); headers.put("Origin", originValue); } }; ClientEndpointConfig clientConfig = ClientEndpointConfig.Builder.create() .configurator(configurator) .build(); try { webSocketContainer.connectToServer(this, clientConfig, new URI(IP)); } catch (Exception e) { ... } }

My computer has a few IP addresses. I want to send a WebSocket request from selected IP - I want to bind the WebSocket to the specific local IP. Is it possible to do? Should I use another library?

EDIT: I found netty - it allows to set the local IP address manually.

最满意答案

我相信操作系统将选择本地地址 - 基于本地接口的路由表。

如果您有多个IP都可以到达目标主机,那么您可以通过要绑定的本地IP配置到该主机的(静态)路由。

I used proxy instead of selecting IP for the request.

更多推荐