websocket协议,用jettyy9实现的一个简单的websocket服务器和客户端

websocket协议,用jettyy9实现的一个简单的websocket服务器和客户端  日期:2013-11-22 浏览:17
jetty官网上的例子是不能直接用的,而且有点语焉不详,今天鼓捣了半天,终于弄出来一个可用的server和client,特此分享。

服务端

与常规服务端的初始化、运行代码是一致的,只是这里使用了WebSocketHandler,而不是常规的ServletContextHandler,这个handler里面包含的MyEchoSocket可以处理与客户端的链接、数据传输等事件

代码如下:



java代码
package websocket;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import org.eclipse.jetty.websocket.server.WebSocketHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

public class SimpleWebsocketService
{
    static public class MyEchoSocket implements WebSocketListener
    {
        Session session;
        boolean isInit = false;
        @Override
        public void onWebSocketBinary(byte[] arg0, int arg1, int arg2)
        {
            System.out.println("onWebSocketBinary");


           
        }

        @Override
        public void onWebSocketClose(int arg0, String arg1)
        {
            System.out.println("onWebSocketClose");
           
        }

        @Override
        public void onWebSocketConnect(Session arg0)
        {
            System.out.println("onWebSocketConnect");
            System.out.println(arg0.getUpgradeRequest().getHeader("index"));
//            this.session = arg0;
           
            if(!isInit)
            {
                new sendThread(arg0).start();
            }
        }

        @Override
        public void onWebSocketError(Throwable arg0)
        {
            System.out.println("onWebSocketError");
           
        }

        @Override
        public void onWebSocketText(String arg0)
        {
            System.out.println("onWebSocketText, content:" + arg0);
        }

    }
   
    static class sendThread extends Thread
    {
        Session session;
        sendThread(Session session)
        {
            this.session = session;
        }
       
        public void run()
        {
            new Timer().schedule(new TimerTask(){

                @Override
                public void run()
                {
                    Future<Void> fut;
                    fut = session.getRemote().sendStringByFuture("Hello");
                    try
                    {
                        fut.get(2, TimeUnit.SECONDS);
                       
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                       
                        fut = session.getRemote().sendStringByFuture(df.format(new Date()));
                        fut.get(2, TimeUnit.SECONDS);
                    }
                    catch (InterruptedException | ExecutionException | TimeoutException e)
                    {
                        e.printStackTrace();
                    }

//                    session.close(StatusCode.NORMAL, "I'm done");
                   
                }}, 1000, 1000);
           
        }
    }

    public static void main(String args[])
    {
        Server server = new Server(7778);
       
        WebSocketHandler  wsHandler = new WebSocketHandler(){
            @Override
            public void configure(WebSocketServletFactory factory)
            {
                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();
        }
       
    }

}


websocket的客户端链接与普通的http client相仿,但是client要用websocket特有的WebSocketClient,需要实现WebSocketListener接口,才能与服务端互连



java代码
package websocket;

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://10.66.90.79: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();
            request.setHeader("index", "3");
            client.connect(socket, echoUri, request);

            System.out.printf("Connecting to : %s%n", echoUri);
            socket.awaitClose(1000, TimeUnit.SECONDS);
        }
        catch (Throwable t)
        {
            t.printStackTrace();
        }
        finally
        {
            try
            {
                client.stop();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}


java代码
package websocket;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;

public class SimpleEchoSocket implements WebSocketListener
{
    private final CountDownLatch closeLatch;


    private Session session;

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

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

    @OnWebSocketClose
    public void onClose(int statusCode, String reason)
    {
        System.out.printf("Connection closed: %d - %s%n", statusCode, reason);
        this.session = null;
        this.closeLatch.countDown();
    }

    @OnWebSocketConnect
    public void onConnect(Session session)
    {
        System.out.printf("Got connect: %s%n", session);
        this.session = session;
        try
        {
            Future<Void> fut;
            fut = this.session.getRemote().sendStringByFuture("Hello");
            fut.get(2, TimeUnit.SECONDS);
            fut = session.getRemote().sendStringByFuture("Thanks for the conversation.");
            fut.get(2, TimeUnit.SECONDS);
            this.session.close(StatusCode.NORMAL, "I'm done");
        }
        catch (Throwable t)
        {
            t.printStackTrace();
        }
    }

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

    @Override
    public void onWebSocketBinary(byte[] arg0, int arg1, int arg2)
    {
        System.out.printf("onWebSocketBinary");
       
    }

    @Override
    public void onWebSocketClose(int arg0, String arg1)
    {
        System.out.printf("onWebSocketClose");
       
    }

    @Override
    public void onWebSocketConnect(Session session)
    {
//        session.getUpgradeRequest()
        System.out.printf("Got connect: %s%n", session);
        this.session = session;
       
        try
        {
            Future<Void> fut;
            fut = session.getRemote().sendStringByFuture("Hello");
            fut.get(2, TimeUnit.SECONDS);
            fut = session.getRemote().sendStringByFuture("Thanks for the conversation.");
            fut.get(2, TimeUnit.SECONDS);
//            session.close(StatusCode.NORMAL, "I'm done");
        }
        catch (Throwable t)
        {
            t.printStackTrace();
        }
       
    }

    @Override
    public void onWebSocketError(Throwable arg0)
    {
        System.out.printf("onWebSocketError");
       
    }

    @Override
    public void onWebSocketText(String arg0)
    {
        System.out.println("onWebSocketText, content:" + arg0);
       
    }
}

你可能感兴趣的:(websocket)