CshBBrain开发示例
1.服务器定时推送广播消息
服务器每隔10秒钟将服务器的当前时间所对应的毫秒数发送给客户度,客户端接收服务器发送的消息并在网页上显示出来。
1.1 我们创建一个线程来每隔10秒发送一个消息:
protected void startBroadMessage(){// 定时发送广播消息的线程
while(true){
try{
Response rs = new Response();// 创建一个响应消息
String msg = "current datetime of server current datetime of server current datetime of server current datetime of server current datetime of server current datetime of server: " + System.currentTimeMillis();
//System.out.println(msg);
rs.setBody(msg);// 给响应消息设置内容
MasterServer.addBroadMessage(rs);// 将要发送的消息广播出去
broadMessageThread.sleep(10000);// 线程睡眠10秒钟
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
1.2 启动服务器时,启动广播线程:
BroadThread.getInstance();// 创建广播线程
1.3 完整代码:
1.3.1 消息广播线程:
package com.jason.server.ws.biz;
import com.jason.server.Response;
import com.jason.server.MasterServer;
/**
* <li>类型名称:
* <li>说明:
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2012-8-24
* <li>修改人:
* <li>修改日期:
*/
public class BroadThread {
private static BroadThread broadThread= new BroadThread();
private Thread broadMessageThread;// 发送广播消息的线程
public static BroadThread getInstance(){
return broadThread;
}
private BroadThread(){
//
消息广播线程
Runnable writeDistributeRunner = new Runnable(){
public void run(){
try{
startBroadMessage();
}catch(Exception e){
e.printStackTrace();
}
}
};
this.broadMessageThread = new Thread(writeDistributeRunner);
this.broadMessageThread.setName("广播消息生成线程");
this.broadMessageThread.start();
}
protected void startBroadMessage(){
while(true){
try{
Response rs = new Response();
String msg = "current datetime of server current datetime of server current datetime of server current datetime of server current datetime of server current datetime of server: " + System.currentTimeMillis();
//System.out.println(msg);
rs.setBody(msg);
MasterServer.addBroadMessage(rs);
broadMessageThread.sleep(10000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
1.3.2 启动消息广播线程
package com.jason.server.ws;
import java.io.IOException;
import com.jason.server.MasterServer;
import com.jason.server.ws.biz.BroadThread;
/**
* <li>类型名称:
* <li>说明:websocket服务器入口类。
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-18
* <li>修改人:
* <li>修改日期:
*/
public class Server{
/**
* <li>方法名:main
* <li>@param args
* <li>返回类型:void
* <li>说明:WebSocket服务器,设置websocketdecoder,websocketProcess,websocketcoder给服务器
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-18
* <li>修改人:
* <li>修改日期:
*/
public static void main(String[] args){
try{
new MasterServer(new WebSocketCoder(), new WebSocketDecoder(), new Processer());
BroadThread.getInstance();
}catch(IOException e){
e.printStackTrace();
}
}
}
2.客户端与服务器相互发送消息
用户在网页上输入一个名字,提交到服务器,服务器回返回"Hello" + 提交的名字。
2.1 重写Service类中的 public Response service(Client sockector, HashMap<String, String> requestData)方法:
public Response service(Client sockector, HashMap<String, String> requestData){
if(requestData == null){
return null;
}
Response responseMessage = null;
try{
if(!MyStringUtil.isBlank(requestData.get(Constants.HANDSHAKE))){
responseMessage = Response.msgOnlyBody(requestData.get(Constants.FILED_MSG));
}else{
responseMessage = Response.msgOnlyBody("Hello," + requestData.get(Constants.FILED_MSG));// 将收到的人名前添加hello问候语
}
}catch(Exception e){
e.printStackTrace();
responseMessage = Response.msgOnlyBody("500处理失败了");
}
return responseMessage;
}
2.2 Service类完整代码:
/**
* <li>文件名:Service.java
* <li>说明:
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-27
* <li>修改人:
* <li>修改日期:
*/
package com.jason.server.ws.biz;
import java.util.HashMap;
import com.jason.server.Client;
import com.jason.server.Response;
import com.jason.util.MyStringUtil;
/**
* <li>类型名称:
* <li>说明:业务处理类
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-11-27
* <li>修改人:
* <li>修改日期:
*/
public class Service{
private static Service service = new Service();// 服务单实例;// 服务单实例
public static Service getInstance(){
return service;
}
private Service(){}
/**
*
* <li>方法名:service
* <li>@param requestData
* <li> @return
* <li>返回类型:ResponseMessage
* <li>说明:业务处理入口方法,对各种接口的请求进行处理
* <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
* <li>创建日期:2011-12-5
* <li>修改人:
* <li>修改日期:
*/
public Response service(Client sockector, HashMap<String, String> requestData){
if(requestData == null){
return null;
}
Response responseMessage = null;
try{
if(!MyStringUtil.isBlank(requestData.get(Constants.HANDSHAKE))){
responseMessage = Response.msgOnlyBody(requestData.get(Constants.FILED_MSG));
}else{
responseMessage = Response.msgOnlyBody("Hello," + requestData.get(Constants.FILED_MSG));
}
}catch(Exception e){
e.printStackTrace();
responseMessage = Response.msgOnlyBody("500处理失败了");
}
return responseMessage;
}
}
2.3 客户端页面代码:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="minimum-scale=1.0,maximum-scale=1,width=device-width,user-scalable=no" />
<title>首页</title>
<!--link rel="stylesheet" type="text/css" media="all" href="css/style.css" /-->
<link rel="stylesheet" type="text/css" media="all and (orientation:portrait)" href="css/style.css" />
<link rel="stylesheet" type="text/css" media="all and (orientation:landscape)" href="css/style_land.css"/>
<script src="js/scrollpic.js" type="text/javascript"></script>
</head>
<body>
<section class="nav">
<div class="subNav">
<div class="slipMarquee" id="stock">
</div>
<div>
<input type="text" id="txt" />
<button value="send" onclick="send();">send</button>
</div>
</div>
</section>
<script language="javascript" type="text/javascript">
window.WebSocket = window.WebSocket || window.MozWebSocket;
var socket = new WebSocket("ws://192.168.1.222:9090/echo"); // 注意这里的ip地址改为你自己的地址,创建sockect客户端
socket.onopen = function(){
//socket.send('i am client');
socket.onclose = function(e){// 关闭连接处理事件
alert('close the socket');
};
socket.onerror = function(msg){// 出错处理事件
alert('error:' + msg );
};
};
socket.onmessage = function(e) {// 收到消息处理事件,将收到的内容以红色显示在页面上
document.getElementById('stock').innerHTML = '<font color =red>' + event.data + '</font>';
};
function send(){// 发送输入的人名
socket.send(document.getElementById('txt').value);
}
</script>
</body>
</html>