Jetty9-implemented Java version of WebcokeT server and client

Continued from the above, “A brief analysis of the websocket protocol”. Share the webcoket server and client demo based on jetty9 to implement java version.
There is no theory, not much to say, the code is here.
Preparation:
Create a new maven project, and import the pom file:


org.eclipse.jetty.websocket
< artifactId>websocket-client
9.4.6.v20170531


org.eclipse.jetty.websocket
websocket-server
9.4.6.v20170531


org.eclipse.jetty.websocket
websocket-api
9.4.6.v20170531


Server implementation:
Server startup class:
“”
package jasonleewebsocket.websocket.server;

import org.eclipse.jetty.server. Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.websocket.server.WebSocketHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

public class WebSocketServerTest{
public static void main(String args[]) {
Server server = new Server(7778);
WebSocketHandler wsHandler = new WebSocketHandler(){
@Override
public void configure(WebSocketServletFactory factory)
{
// Register a custom event listener
factory.register(MyEchoSocket.class);
}
};
ContextHandler context = new ContextHandler();
context.setContextPath(“/echo”) ;
context.setHandler(wsHandler);

server.setHandler(wsHandler); 
try
{
server.start();
server .join();
}
catch (Exception e)
{
e.printStackTrace();
}
}

}

Custom monitor class:

package jasonleewebsocket.websocket.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.jetty .websocket.api.Session;
import org.eclipse.je tty.websocket.api.WebSocketListener;
import org.eclipse.jetty.websocket.api.WriteCallback;

public class MyEchoSocket implements WebSocketListener{
//Maintain the session
private static final Set< Session> sessions =
Collections.synchronizedSet( new HashSet< Session >() );
private Session session;

//The connection is closed, remove the session list
public void onWebSocketClose(int statusCode, String reason) {
System.out.println(reason);
sessions.remove(this.session);
this.session = null;
}

//Save the session after establishing a connection
public void onWebSocketConnect(Session session) {
this.session = session;
System.out.println(session. isOpen());
sessions.add(session);
}

//Error handling
public void onWebSocketError(Throwable cause) {
System .out.println(cause.getMessage());

}

//Receive string type messages and notify all clients
public void onWebSocketBinary( byte[] payload, int offset, int len) {
System.out.println("W ebSocketBinary:"+new String(payload));
for(final Session session: sessions){
session.getRemote().sendBytes(ByteBuffer.wrap(payload), new WriteCallback() {
//Callback processing is sent successfully
public void writeSuccess() {
System.out.println("success");
}

public void writeFailed (Throwable x) {
System.out.println("senderror:"+x.getMessage());
}
});
}
}< br />
//Receive string type messages and forward them to all clients
public void onWebSocketText(String message) {
System.out.println("text message:"+message );
try {
for(final Session session: sessions){
session.getRemote().sendString("server to convert text:"+message);
}< br />} catch (IOException e) {
e.printStackTrace();
}
}

}

Client implementation :
Client startup class:

package jasonleewebsocket.websoc ket.client;

import java.net.URI;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;

public class SimpleEchoClient
{
public static void main(String[] args)
{
String destUri = “ws://localhost:7778/echo”;
if (args.length> 0)
{
destUri = args[0];
}

WebSocketClient client = new WebSocketClient();
SimpleEchoSocket socket = new SimpleEchoSocket();
try
{
client.start();

URI echoUri = new URI(destUri);
ClientUpgradeRequest request = new ClientUpgradeRequest();
client.connect(socket,echoUri,request);
System.out.printf("Connecting to:% s%n",echoUri);
// wait for closed socket connection.
socket.awaitClose(500,TimeUnit.SECONDS);
}
catch (Throwable t)< br /> {
t.printStackTrace();
}
finally
{
try
{
client.stop();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

}
< br> Client monitoring class:

package jasonleewebsocket.websocket.client;

import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

@WebSocket
public class SimpleEchoSocket {

private final CountDownLatch closeLatch;

public SimpleEchoSocket() {
this.closeLatch = new CountDownLatch(1);
}

public boolean awaitClose( int duration, TimeUnit unit) throws InterruptedException {
return this.closeLatch.await(duration, unit);
}

@OnWebSocketMessage
public void onMessage(String msg ) {
System.out.printf("Got msg: %s%n", msg);
}

@OnWebSocketMessage
public void onMessage(byte[ ] buffer, int offset, int length) {
System.out.printf("Got msg: %s%n", new String(buffer));
}

@OnWebSocketConnect
public void onConnect(Session session) {
System.out.printf("Got connect: %s%n", session);
try {
session.getRemote ().sendBytes(ByteBuffer.wrap("test byte".getBytes()));
session.getRemote().sendString("456");
} catch (Throwable t) {
t.printStackTrace();
}
}

}

“”

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 4589 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.