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

演示为websocket赋值id , 这样在收到消息的情况下 , 方便获取到消息的来源package com.test.test2;/** * A simple WebSocketServer implementation. Keeps track of a "chatroom". ** Shows how to use the attachment for a WebSocket. This example just uses a simple integer as ID. * Setting an attachment also works in the WebSocketClient */public class ChatServerAttachmentExample extends WebSocketServer {Integer index = 0;public ChatServerAttachmentExample(int port) throws UnknownHostException {super(new InetSocketAddress(port));}public ChatServerAttachmentExample(InetSocketAddress address) {super(address);}@Overridepublic void onOpen(WebSocket conn, ClientHandshake handshake) {conn.setAttachment(index); //Set the attachment to the current indexindex++;// Get the attachment of this connection as IntegerSystem.out.println(conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room! ID: "+ conn.getAttachment());}@Overridepublic void onClose(WebSocket conn, int code, String reason, boolean remote) {// Get the attachment of this connection as Integer//这里获取到前面设备连接时赋值的idSystem.out.println(conn + " has left the room! ID: " + conn.getAttachment());}@Overridepublic void onMessage(WebSocket conn, String message) {System.out.println(String.valueOf(conn.getAttachment()) + ": " + message);}@Overridepublic void onMessage(WebSocket conn, ByteBuffer message) {System.out.println(conn + ": " + message);}public static void main(String[] args) throws InterruptedException, IOException {int port = 1234; // 843 flash policy porttry {port = Integer.parseInt(args[0]);} catch (Exception ex) {}ChatServerAttachmentExample s = new ChatServerAttachmentExample(port);s.start();System.out.println("ChatServer 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;}}}@Overridepublic void onError(WebSocket conn, Exception ex) {ex.printStackTrace();if (conn != null) {// some errors like port binding failed may not be assignable to a specific websocket}}@Overridepublic void onStart() {System.out.println("Server started!");}}设置访问websocket的设备的需要携带的参数package com.test.test2;/** * This example shows how to reject a handshake as a server from a client. ** For this you have to override onWebsocketHandshakeReceivedAsServer in your WebSocketServer class */public class ServerRejectHandshakeExample extends ChatServer {public ServerRejectHandshakeExample(int port) {super(new InetSocketAddress(port));}@Overridepublic ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft,ClientHandshake request) throws InvalidDataException {ServerHandshakeBuilder builder = super.onWebsocketHandshakeReceivedAsServer(conn, draft, request);//In this example we don't allow any resource descriptor ( "ws://localhost:8887/?roomid=1 will be rejected but ws://localhost:8887 is fine)if (!request.getResourceDescriptor().equals("/")) {throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Not accepted!");}//If there are no cookies set reject it as well.if (!request.hasFieldValue("Cookie")) {throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Not accepted!");}//If the cookie does not contain a specific valueif (!request.getFieldValue("Cookie").equals("username=nemo")) {throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Not accepted!");}//If there is a Origin Field, it has to be localhost:8887if (request.hasFieldValue("Origin")) {if (!request.getFieldValue("Origin").equals("localhost:8887")) {throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Not accepted!");}}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) {}ServerRejectHandshakeExample s = new ServerRejectHandshakeExample(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;}}}}


推荐阅读