java webSocket 开发,个人心得,有什么改进的地方可以提出来

来源:互联网 发布:我的老婆是网络女主播 编辑:程序博客网 时间:2024/04/27 14:45

用到的Jar包(apache-tomcat-7.0.40):

tomcat-coyote.jar

catalina.jar

Java代码:


//第一个java类​

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.StreamInbound;

import org.apache.catalina.websocket.WebSocketServlet;

public class WebSocketServer extends WebSocketServlet {

private static final long serialVersionUID = 1L;

private static Map> map = new HashMap>();

@Override

protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) {

if(map.get("computer") == null) {

map.put("computer", new ArrayList());

}

if(map.get("mobile") == null) {

map.put("mobile", new ArrayList());

}

//当前推送功能

String function = request.getParameter("function");

//推送到--功能

String pushToFunction = request.getParameter("pushToFunction");

//socket对象(电脑Or手机)

String obj = request.getParameter("obj");

//推送对象

String pushToObj = request.getParameter("pushToObj");

//会话ID

String sessionId = request.getSession().getId();

return new MessageInbound(function, pushToFunction, obj,pushToObj,sessionId, map);

}

public static Map> getMap() {

return map;

}

}


//第二个java类

import java.io.IOException;

import java.io.InputStream;

import java.io.Reader;

import java.nio.CharBuffer;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.apache.catalina.websocket.StreamInbound;

import org.apache.catalina.websocket.WsOutbound;

import org.springframework.util.StringUtils;

public class MessageInbound extends StreamInbound {

private String function = "";

    private String pushToFunction = "";

    private String obj = "";

    private String pushToObj = "";

    private String sessionId = "";

    private Map> map = new HashMap>();

    public MessageInbound(){}

    

    public MessageInbound(String _function, String _pushToFunction, String _obj, String _pushToObj, String _sessionId, Map> _map) {

    if(!StringUtils.hasText(_obj)) {

    _obj = "computer";

    }

   

    if(!StringUtils.hasText(_pushToObj)) {

    _pushToObj = "computer";

    }

   

    if(!StringUtils.hasText(_function)) {

    _function = "";

    }

   

    if(!StringUtils.hasText(_pushToFunction)) {

    _pushToFunction = "";

    }

   

    this.obj = _obj;

    this.pushToObj = _pushToObj;

    this.function = _function;

        this.pushToFunction = _pushToFunction;

        this.sessionId = _sessionId;

        this.map = _map;

    }

    //发送消息自动调用该方法

    @Override

    protected void onTextData(Reader reader) throws IOException {

        char[] chArr = new char[4096];

        int len = reader.read(chArr);

        String msg = String.copyValueOf(chArr, 0, len);

        

        List pushObjList = getMap().get(pushToObj);

        if(pushObjList != null) {

        for (MessageInbound msgi : pushObjList) {

        //只推送在当前功能页面

        if(this.pushToFunction.equals(msgi.getFunction())) {

        msgi.getWsOutbound().writeTextMessage(CharBuffer.wrap(msg));

        }

    }

        }

    }

    //打开连接

    @Override

    protected void onOpen(WsOutbound outbound) {

    List msgiList = getMap().get(obj);

    msgiList.add(this);

    getMap().put(obj, msgiList);

   

        super.onOpen(outbound);

    }

    //关闭连接

    @Override

    protected void onClose(int status) {

    List msgiList = getMap().get(obj);

    List removeObj = new ArrayList();

    if(msgiList != null) {

    for (MessageInbound msgi : msgiList) {

    if(msgi.sessionId.equals(this.sessionId)) {

    removeObj.add(msgi);

    }

    }

    }

    msgiList.removeAll(removeObj);

        super.onClose(status);

    }

    @Override

    protected void onBinaryData(InputStream arg0) throws IOException {

    }

public String getFunction() {

return function;

}

public void setFunction(String function) {

this.function = function;

}

public String getPushToFunction() {

return pushToFunction;

}

public void setPushToFunction(String pushToFunction) {

this.pushToFunction = pushToFunction;

}

public String getObj() {

return obj;

}

public void setObj(String obj) {

this.obj = obj;

}

public String getPushToObj() {

return pushToObj;

}

public void setPushToObj(String pushToObj) {

this.pushToObj = pushToObj;

}

public String getSessionId() {

return sessionId;

}

public void setSessionId(String sessionId) {

this.sessionId = sessionId;

}

public Map> getMap() {

return map;

}

public void setMap(Map> map) {

this.map = map;

}

}


//因为是利用servlet开发,所以需要在web.xml里配置servlet​

web.xml:

    webSocketServer

    com.define.zhsmw.util.WebSocketServer

    webSocketServer

    /webSocketServer


javascript:

可以新建一个webSocket.js,或者直接在页面上写

// WebSocket演示对象

var socketObj = {

socket : null,  // WebSocket连接对象

host : ((window.location.protocol == 'http:') ? 'ws://' : 'wss://') + window.location.host + '/webSocketServer?',      // WebSocket连接 url----servlet地址

connect : function() {  // 连接服务器

window.WebSocket = window.WebSocket || window.MozWebSocket;

if (!window.WebSocket) {    // 检测浏览器支持

console.log('Error: WebSocket is not supported .');

return;

}

this.socket = new WebSocket(this.host); // 创建连接并注册响应函数

this.socket.onopen = function(){console.log("websocket is opened .");};

this.socket.onmessage = function(message) {

//conten: message.data;

};

this.socket.onerror = function(e)

{

alert("推送失败!\n" + e);

}

this.socket.onclose = function(){

console.log("websocket is closed .");

socketObj.socket = null; // 清理

};

},

send : function(message) {  // 发送消息方法

if (this.socket) {

this.socket.send(message);

return true;

}

console.log('please connect to the server first !!!');

return false;

}

};

页面调用:

window.onload=function(){

socketObj.host += $("#pushParamFrm").serialize();

//连接

socketObj.connect();

//重写获取消息的方法

socketObj.socket.onmessage = function(message) {

var reg1=new RegExp(/^\{\"id\":/);

var reg2=new RegExp(/\}$/);

if(reg1.test(message.data) && reg2.test(message.data)) {

var t = JSON.parse(message.data);

if(t.type == "update_terminalRecordFault_status") {

$("#" + t.id + "_status").html("已解决");

   $("#" + t.id + "_work").replaceWith("故障派工");

}

}

};

}


//你可以自己写一个按钮,然后触发这个方法,参数可以自己定义​

function msgTest(terminal_id,terminal_code,address,fault_info) {

socketObj.send('{"id":"' +terminal_id + '",' + 

'"terminal_code":"' + terminal_code + '",' + 

'"address":"' + address + '",' + 

'"fault_info":"' + fault_info + '"}'

  );

}


完成后,tomcat启动可能会出现如下报错:

Tomacat7启动报错如下:

java.lang.NoSuchMethodException: org.apache.catalina.deploy.WebXml addFilter

解决方法为:

在Tomacat7的context.xml文件里的中加上

解释:

Loader对象可出现在Context中以控制Java类的加载。

属性:delegate、含义:True代表使用正式的Java代理模式(先询问父类的加载器);

false代表先在Web应用程序中寻找。

默认值:FALSE





以上是利用tomcat7里的webSocket开发的。如果觉得麻烦,可以尝试下使用插件,例如goeasy推送,单纯的页面推送,直接使用goeasy.js(没有可以到https://cdn.goeasy.io/goeasy.js复制下来新建文件)这个js就可以了,前提是你电脑需要连接网络,能上网就行。


利用goeasy推送开发(使用goeasy开发,必须要连接网络,

因为使用的是 https://goeasy.io/goeasy/publish 推送服务器):

首先获取appkey(要去官网上注册一个账号(https://goeasy.io/www/home.jsp),然后添加一个app获取appKey):

channel:

channel属性,也就相当于身份证一样,只要双方对上channel就可以接收到对方的消息,

appkey作用就是在所有项目中用到这个appKey的都会收到消息,无论是不是在本地项目。

javascript方面:

导入goeasy.js,没有可以到https://cdn.goeasy.io/goeasy.js复制下来新建文件

先定义好对象,这个是接收消息。

var goEasy = new GoEasy({

appkey: "${appKey}"

});

goEasy.subscribe({

channel: "my_channel",

onMessage: function (message) {

alert("收到信息啦");

});

发送消息:

goEasy.publish({

channel: "mobile",

message: "你好吗?",

onSuccess:function(){

alert("消息发布成功。");

},

onFailed: function (error) {

alert("消息发送失败,错误编码:"+error.code+" 错误信息:"+error.content);

}

});

java(或安卓)方面:

需要导入以下jar包

SDK 下载地址: https://cdn.goeasy.io/sdk/goeasy-0.1.jar

添加依赖包:

gson:     http://repo.maven.apache.org/maven2/com/google/code/gson/gson/2.3.1/gson-2.3.1.jar

slf4j-api:http://repo.maven.apache.org/maven2/org/slf4j/slf4j-api/1.7.2/slf4j-api-1.7.2.jar

private static final String APPKEY = "e922e2bd-ba6a-4576-9a1d-65704dd31082";

发送消息:

GoEasy goEasy = new GoEasy("my_appkey");

goEasy.publish("my_channel", "Hello, GoEasy!");

这是安卓的发送消息:

GoEasy goEasy = new GoEasy("my_appkey", androidApplication);

goEasy.publish("my_channel","Hello, GoEasy!");

这是安卓的接收消息:

GoEasy goEasy = new GoEasy("my_appkey", androidApplication);

goEasy.subscribe("my_channel", new SubscribeListener() {

@Override

public void onMessage(GoEasyClientMessage clientMessage) {

System.out.println("Message:" + clientMessage.getContent());

}

});

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 自动挡的车如果刹车失灵怎么办 手动挡汽车刹车失灵怎么办 车辆没有年检出了交通事故怎么办 跟着大货车闯了红灯怎么办 在万家金服买的电子产品坏了怎么办 汽车被油笔画了怎么办? 挂到别人车跑了怎么办 浪琴手表保修卡掉了怎么办 事故车辆维修和报废怎么办 4.2货车拉缸了怎么办 工作中与同事发生矛盾怎么办 和领导关系闹僵怎么办 内倒窗户卡住了怎么办 支付宝存在安全风险怎么办 地铁车站空调坏了怎么办 面试防汛值班发生灾情你怎么办 怀孕上班路途太远怎么办 硕士错过校招应该怎么办 收银员收多了钱怎么办 商铺贷款批不了怎么办 铁路局的门面乱收房租怎么办 酒店夜审房费多过怎么办 夜审房价录多了怎么办 做工地拿不到钱怎么办 赢了官司拿不到钱怎么办 工地上拿不到钱怎么办 做了工拿不到钱怎么办 高速公路上车没油了怎么办 高铁乘务员年龄大了怎么办 总公司跑路了分公司怎么办 坐车久了耳朵懵怎么办 过完隧道耳朵疼怎么办 护照还在大使馆需要出国怎么办 护照在大使馆不返回怎么办 美国面签迟到了怎么办 成都美签迟到了怎么办 签证电调没人接怎么办 单位没有抬头纸怎么办在职证明 出国签证无银行流水怎么办 铁路职工得癌症后工作怎么办 去泰国不会泰语和英语怎么办