轻拔琴弦|java-websocket示例项目,可以直接使用( 五 )


轻拔琴弦|java-websocket示例项目,可以直接使用package com.test.test2;/** * Simple example to reconnect blocking and non-blocking. */public class ReconnectClientExample {public static void main(String[] args) throws URISyntaxException, InterruptedException {ExampleClient c = new ExampleClient(new URI("ws://localhost:8887"));//Connect to a server normallyc.connectBlocking();c.send("hi");Thread.sleep(10);c.closeBlocking();//Disconnect manually and reconnect blockingc.reconnectBlocking();c.send("it's");Thread.sleep(10000);c.closeBlocking();//Disconnect manually and reconnectc.reconnect();Thread.sleep(100);c.send("me");Thread.sleep(100);c.closeBlocking();}}这个例子演示了如何为您的连接使用特定的sec - websocket协议 。package com.test.test2;/** * This example demonstrates how to use a specific Sec-WebSocket-Protocol for your connection. */public class SecWebSocketProtocolClientExample {public static void main(String[] args) throws URISyntaxException {// This draft only allows you to use the specific Sec-WebSocket-Protocol without a fallback.Draft_6455 draft_ocppOnly = new Draft_6455(Collections.emptyList(),Collections.singletonList(new Protocol("ocpp2.0")));// This draft allows the specific Sec-WebSocket-Protocol and also provides a fallback, if the other endpoint does not accept the specific Sec-WebSocket-ProtocolArrayList protocols = new ArrayList();protocols.add(new Protocol("ocpp2.0"));protocols.add(new Protocol(""));Draft_6455 draft_ocppAndFallBack = new Draft_6455(Collections.emptyList(),protocols);ExampleClient c = new ExampleClient(new URI("ws://echo.websocket.org"), draft_ocppAndFallBack);c.connect();}}服务器在响应客户端时 , 附带额外的数据package com.test.test2;/** * This example shows how to add additional headers to your server handshake response ** For this you have to override onWebsocketHandshakeReceivedAsServer in your WebSocketServer class ** We are simple adding the additional header "Access-Control-Allow-Origin" to our server response */public class ServerAdditionalHeaderExample extends ChatServer {public ServerAdditionalHeaderExample(int port) {super(new InetSocketAddress(port));}@Overridepublic ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft,ClientHandshake request) throws InvalidDataException {ServerHandshakeBuilder builder = super.onWebsocketHandshakeReceivedAsServer(conn, draft, request);builder.put("Access-Control-Allow-Origin", "*");return builder;}public static void main(String[] args) throws InterruptedException, IOException {int port = 8887; // 843 flash policy porttry {port = Integer.parseInt(args[0]);} catch (Exception ex) {}ServerAdditionalHeaderExample s = new ServerAdditionalHeaderExample(port);s.start();System.out.println("Server started on port: " + s.getPort());BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));while (true) {String in = sysin.readLine();s.broadcast(in);if (in.equals("exit")) {s.stop(1000);break;}}}}


推荐阅读