packagedemo.wsdemo;importjava.net.URI;importjava.net.URISyntaxException;importjava.util.Map;importjava.util.Scanner;importorg.java_websocket.client.WebSocketClient;importorg.java_websocket.drafts.Draft;importorg.java_websocket.handshake.ServerHandshake;publicclassWsClientextendsWebSocketClient{publicWsClient(URI serverUri,Draft draft){super(serverUri, draft);}publicWsClient(URI serverURI){super(serverURI);}publicWsClient(URI serverUri,Map<String,String> httpHeaders){super(serverUri, httpHeaders);}@OverridepublicvoidonOpen(ServerHandshake handshakedata){send("Hello, it is me. Mario :)");System.out.println("opened connection");// if you plan to refuse connection based on ip or httpfields overload: onWebsocketHandshakeReceivedAsClient}@OverridepublicvoidonMessage(String message){System.out.println("received: "+ message);}@OverridepublicvoidonClose(int code,String reason,boolean remote){// The close codes are documented in class org.java_websocket.framing.CloseFrameSystem.out.println("Connection closed by "+(remote ?"remote peer":"us")+" Code: "+ code +" Reason: "+ reason);}@OverridepublicvoidonError(Exception ex){
ex.printStackTrace();// if the error is fatal then onClose will be called additionally}publicstaticvoidmain(String[] args)throwsURISyntaxException{WsClient c =newWsClient(newURI("ws://localhost:8887"));Scanner scanner =newScanner(System.in);newThread(c::connect).start();while(true){String input = scanner.nextLine();
c.send(input);}}}
服务端
packagedemo.wsdemo;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.InetSocketAddress;importjava.net.UnknownHostException;importjava.nio.ByteBuffer;importjava.util.Collections;importorg.java_websocket.WebSocket;importorg.java_websocket.drafts.Draft;importorg.java_websocket.drafts.Draft_6455;importorg.java_websocket.handshake.ClientHandshake;importorg.java_websocket.server.WebSocketServer;publicclassWsServerextendsWebSocketServer{publicWsServer(int port){super(newInetSocketAddress(port));}publicWsServer(InetSocketAddress address){super(address);}publicWsServer(int port,Draft_6455 draft){super(newInetSocketAddress(port),Collections.<Draft>singletonList(draft));}@OverridepublicvoidonOpen(WebSocket conn,ClientHandshake handshake){
conn.send("Welcome to the server!");//This method sends a message to the new clientbroadcast("new connection: "+ handshake
.getResourceDescriptor());//This method sends a message to all clients connectedSystem.out.println(
conn.getRemoteSocketAddress().getAddress().getHostAddress()+" entered the room!");}@OverridepublicvoidonClose(WebSocket conn,int code,String reason,boolean remote){broadcast(conn +" has left the room!");System.out.println(conn +" has left the room!");}@OverridepublicvoidonMessage(WebSocket conn,String message){broadcast(message);System.out.println(conn +": "+ message);}@OverridepublicvoidonMessage(WebSocket conn,ByteBuffer message){broadcast(message.array());System.out.println(conn +": "+ message);}publicstaticvoidmain(String[] args)throwsInterruptedException,IOException{int port =8887;// 843 flash policy porttry{
port =Integer.parseInt(args[0]);}catch(Exception ex){}WsServer s =newWsServer(port);
s.start();System.out.println("ChatServer started on port: "+ s.getPort());BufferedReader sysin =newBufferedReader(newInputStreamReader(System.in));while(true){String in = sysin.readLine();
s.broadcast(in);if(in.equals("exit")){
s.stop(1000);break;}}}@OverridepublicvoidonError(WebSocket conn,Exception ex){
ex.printStackTrace();if(conn !=null){// some errors like port binding failed may not be assignable to a specific websocket}}@OverridepublicvoidonStart(){System.out.println("Server started!");setConnectionLostTimeout(0);setConnectionLostTimeout(100);}}