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

本文详细介绍了如何利用Tomcat7和WebSocket实现实时通讯,并提供了使用goeasy推送服务进行消息传递的实例。包括配置Tomcat7、编写WebSocket服务端代码、客户端JavaScript调用方法、以及使用goeasy进行消息发送和接收。同时,提供了Tomcat启动报错的解决方案和goeasy推送的使用指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用到的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());

}

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值