websocket java使用demo。包含客户端与服务端使用

原创
2016/07/06 21:06
阅读数 8.2K

入门使用

服务端代码:

package com.xxg.websocket;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.RemoteEndpoint.Basic;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * @ServerEndpoint 标注的是多实例 的 
 * @author Administrator
 *
 */
@ServerEndpoint("/log")  // 服务点
public class LogWebSocketHandle {
	private int count = 0;
	/**
	 * 新的WebSocket请求开启
	 * 连接建立成功调用的方法
	 * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
	 */
	@OnOpen
	public void onOpen(Session session) {
		System.out.println("onOpen start");		
		try {
		
			Basic basicRemote = session.getBasicRemote();
			URI requestURI = session.getRequestURI();
			basicRemote.sendText(requestURI.getPath()+requestURI.getQuery());
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
		}
	}
	
	/**
	 * 收到客户端消息后调用的方法
	 * @param message 客户端发送过来的消息
	 * @param session 可选的参数
	 */
	@OnMessage
	public void onMessage(String message, Session session){
		System.out.println("client message "+message);
		final Session session1 = session;
		try {
			session.getBasicRemote().sendText(" say count "+(++count));
			session.getBasicRemote().flushBatch();
			
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						while(true){
							session1.getBasicRemote().sendText("hello benny" + (++count)+"\r\n");
							session1.getBasicRemote().flushBatch();
							Thread.sleep(1000);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**
	 * WebSocket请求关闭
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose() {
		System.out.println("onClose end");
	}
	
	/**
	 * 发生错误时调用
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Throwable thr) {
		thr.printStackTrace();
	}
	
	
}

客户端依赖:

<dependency>
    <groupId>org.glassfish.tyrus.bundles</groupId>
    <artifactId>tyrus-standalone-client</artifactId>
    <version>1.13</version>
</dependency>

客户端的类库,千万不要使用下面这段。

<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-client-api</artifactId>
    <version>1.1</version>
</dependency>

如果使用上面的类库会出现下面异常

Exception in thread "main" java.lang.RuntimeException: Could not find an implementation class.
at javax.websocket.ContainerProvider.getWebSocketContainer(ContainerProvider.java:73)
at connect.<init>(connect.java:21)
at test.main(test.java:11)

解决方法:http://stackoverflow.com/questions/27751630/websocket-client-could-not-find-an-implementation-class stackoverflow 上的大牛解释

javax.websocket api is only the specification don't have full implementation you may need to take the jar file tyrus-standalone-client-1.9.jar and try the same example that should solve your problem. i tested with my example and it is working fine.

客户端代码:

package com.xxg.websocket.client;

import java.io.IOException;
import java.net.URI;

import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class WebSocketClient {

	private Session session = null;
	
	private int count = 0;
	
	@OnOpen
	public void onOpen(Session session){
		sendMessage("onOpen hello benny onOpen");
	}
	
	@OnClose
	public void onClose(){
		
	}
	
	@OnMessage
	public void onMessage(String message, Session session){
		System.out.println("server message:"+message);
		if(count <10){
			sendMessage("onMessage hello benny "+(++count));
		}
	}
	
	@OnError
	public void onError(Throwable thr){
		
	}

	public WebSocketClient() {
		super();
	}
	
	public WebSocketClient(URI endpointURI) {
		super();
		try {
			WebSocketContainer container = ContainerProvider.getWebSocketContainer();	// 获得WebSocketContainer
			this.session = container.connectToServer(WebSocketClient.class, endpointURI);	// 该方法会阻塞
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}
	
	
	public void sendMessage(String message){
		try {
			this.session.getBasicRemote().sendText(message);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				this.session.getBasicRemote().flushBatch();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
展开阅读全文
打赏
0
6 收藏
分享
加载中
如果想从服务器端推送消息到客户端的话,个人觉得GoEasy推送还不错,它有Restful API 支持多语言,而且针对java他们还特别做了SDK,使用很简单方便。同时它也支持客户端推送。由于它支持websocket 和polling两种连接方式所以兼顾大多数主流浏览器,低版本的IE浏览器也是支持的,很适合需要快速建立实时web通信的项目。https://goeasy.io相关博客:http://www.cnblogs.com/jishaochengduo/articles/5552645.html
2016/08/08 18:27
回复
举报
更多评论
打赏
1 评论
6 收藏
0
分享
返回顶部
顶部