WebSocketの使用例

6699 ワード

Html 5は、WebSocket socket通信はサービス側とクライアントの間で行われ、いわゆるWebSocketは実際にはHtmlとバックグラウンドサーバの間で行われるメッセージ伝達である.
簡単なWebSocketインスタンスを実装する方法について説明します.
注意:
JDKは1.7以上、tomcatは7以上でなければならない.
SpringのWebsocketへのサポートもSpring 4以降のみ
1、クライアントプログラムの作成

<div class="row-fluid">
	<label>    
	</label>
	<label id="toUserName"></label>
	<div class="span12">
	<textarea rows="4" id="question_text" class="form-control"></textarea>
	</div>
</div>
<div class="row-fluid" style="margin-top: 10px;">
	<button id="btn_send" class="btn btn-default">  </button>
	<button id="btn_cancel" class="btn btn-default">  </button>
</div>
<hr>
<div class="row-fluid">
	<div class="span12" id="discussList">
	</div>
</div>


jsコード




var webSocket =new WebSocket(resourceDomain.replace("http://", "ws://") + 'coder_request?wx101id='+wx101id);
 
webSocket.onerror = function(event) {
onError(event)
};

webSocket.onopen = function(event) {
onOpen(event)
};

webSocket.onmessage = function(event) {
onMessage(event)
};
function onMessage(event) {
	var json =JSON.parse(event.data);
	var div = '<div class="thumbnail">';
	if (json.creator) {
		div = div +'<label>' + json.creator +'</label>';
	}
	div = div + '<div>' + json.content+ '</div>';
	div = div + '</div>';
	$("#discussList").prepend(div);
}

function onOpen(event) {
	userWebsocket = true;
}

function onError(event) {
  	alert(event.data);
}



2、サービス側プログラムの作成

package com.itbuilder.wx.web.socket;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;

import com.itbuilder.framework.ApplicationContextHolder;
import com.itbuilder.framework.util.AssertUtil;
import com.itbuilder.framework.util.JSONUtil;
import com.itbuilder.wx.entity.Wxjc101;
import com.itbuilder.wx.entity.Wxjc102;
import com.itbuilder.wx.service.IWxjc102Service;
import com.itbuilder.wx.web.WebChatPool;


/**
 *       socket
 * @author mrh
 *
 */
@Controller
@ServerEndpoint("/coder_request")
public class CoderRequestSocket {
	
	private IWxjc102Service wx102Service;
	
	/**
	 * LOGGER
	 */
	private static final Logger LOGGER = Logger.getLogger(CoderRequestSocket.class);
	
	

	public CoderRequestSocket() {
		this.wx102Service = ApplicationContextHolder.getBean("wx102Service", IWxjc102Service.class);
	}

	/**
	 *             
	 * @param message
	 * @param session
	 * @throws IOException
	 * @throws InterruptedException
	 */
	@OnMessage
	public void onMessage(String content, Session session) {
	    try {
	    	String toUserName = this.getToUserName(content);
	    	String message = this.getMessage(content);
	    	String wx101id = this.getPoolId(session);
	    	Wxjc102 wx102 = this.wx102Service.doSendMsg(message, toUserName, wx101id);
	    	Wxjc101 wx101 = this.wx102Service.queryWx101(wx101id);
	    	Session reciver = WebChatPool.getSession(wx101id, wx101.getModifier());
			session.getBasicRemote().sendText(JSONUtil.toString(wx102));
			if (AssertUtil.hasValue(reciver) && !reciver.getId().equals(session.getId())) {
				reciver.getBasicRemote().sendText(JSONUtil.toString(wx102));
			}
			reciver = WebChatPool.getSession(wx101id, toUserName);
			if (AssertUtil.hasValue(toUserName) && !reciver.getId().equals(session.getId())) {
				reciver.getBasicRemote().sendText(JSONUtil.toString(wx102));
			}
		} catch (IOException e) {
			LOGGER.error("       sessionId = " + session.getId(), e);
		} catch (Exception e) {
			LOGGER.error("       sessionId = " + session.getId(), e);
		}
	}
	
	/**
	 *        
	 * @param content String
	 * @return String
	 */
	private String getMessage(String content) {
		if (!AssertUtil.hasValue(content)) {
			return null;
		}
		if (!content.contains("&")) {
			return content;
		}
		return content.substring(0, content.lastIndexOf("&"));
	}
	
	/**
	 *        
	 * @param content String
	 * @return String
	 */
	private String getToUserName(String content) {
		if (!AssertUtil.hasValue(content)) {
			return null;
		}
		if (!content.contains("&")) {
			return null;
		}
		return content.substring(content.lastIndexOf("&")+1, content.length());
	}
	
	/**
	 *                   
	 * @param session
	 */
	@OnOpen
	public void onOpen(Session session) {
		String poolId = this.getPoolId(session);
		if (AssertUtil.hasValue(poolId)) {
			WebChatPool.add(poolId, session.getId(), session);
		}
	}
	 
	@OnClose
	public void onClose(Session session) {
		String poolId = this.getPoolId(session);
		if (AssertUtil.hasValue(poolId)) {
			WebChatPool.remvoe(poolId, session.getId());
		}
	}
	
	
	/**
	 *      ID
	 * @param session
	 * @return
	 */
	private String getPoolId(Session session) {
		Map<String, List<String>> paramMap = session.getRequestParameterMap();
		if (AssertUtil.hasValue(paramMap)) {
			List<String> wx101IdList = paramMap.get("wx101id");
			if (AssertUtil.hasValue(wx101IdList)) {
				return wx101IdList.get(0);
			}
		}
		return null;
	}
}