spring-boot整合websocket

2 篇文章 0 订阅
1 篇文章 0 订阅
服务端说明:由于socket的服务貌似无法自动注入服务接口,所以改用jdbc直接访问数据库获取数据:
package 
com.ocl.www.utils;

import java.sql.*;

/**
* Created by Administrator on 2016/12/2.
*/
public class JDBCUntil {

public static Connection getConnection() {

//声明Connection对象
Connection con =  null;
//驱动程序名
String driver = ResourceBundleUtils. getProperty( "jdbc.driver");
//URL指向要访问的数据库名mydata
String url = ResourceBundleUtils. getProperty( "jdbc.url");
//MySQL配置时的用户名
String user = ResourceBundleUtils. getProperty( "jdbc.user");
//MySQL配置时的密码
String password = ResourceBundleUtils. getProperty( "jdbc.password");
//遍历查询结果集
try {
//加载驱动程序
Class. forName(driver);
//1.getConnection()方法,连接MySQL数据库!!
con = DriverManager. getConnection(url, user, password);
return con;
// if(!con.isClosed())
// System.out.println("Succeeded connecting to the Database!");
// //2.创建statement类对象,用来执行SQL语句!!
// Statement statement = con.createStatement();
//要执行的SQL语句
//String sql = "select * from student";
//3.ResultSet类,用来存放获取的结果集!!
//ResultSet rs = statement.executeQuery(sql);
// System.out.println("-----------------");
// System.out.println("执行结果如下所示:");
// System.out.println("-----------------");
// System.out.println(" 学号" + "\t" + " 姓名");
// System.out.println("-----------------");

// String name = null;
// String id = null;
// while(rs.next()){
// //获取stuname这列数据
// name = rs.getString("stuname");
// //获取stuid这列数据
// id = rs.getString("stuid");
// //首先使用ISO-8859-1字符集将name解码为字节序列并将结果存储新的字节数组中。
// //然后使用GB2312字符集解码指定的字节数组。
// name = new String(name.getBytes("ISO-8859-1"),"gb2312");
// //输出结果
// System.out.println(id + "\t" + name);
// }
// rs.close();
// con.close();
catch (ClassNotFoundException e) {
//数据库驱动类异常处理
System. out.println( "Sorry,can`t find the Driver!");
e.printStackTrace();
catch (SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
catch (Exception e) {
//  TODO: handle exception
e.printStackTrace();
finally {
System. out.println( "数据库数据成功获取!!");
}
return con;
}

} 
server端:

package com.ocl.www.controller;

import com.ocl.www.service.LetterService;
import com.ocl.www.utils.JDBCUntil;
import net.sf.json.JSONObject;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import  org.springframework.beans.factory.annotation.Autowired;
import  org.springframework.beans.factory.annotation.Configurable;
import  org.springframework.beans.factory.annotation.Qualifier;

import javax.websocket.*;
import  javax.websocket.server.PathParam;
import  javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import static org.eclipse.jdt.internal.compiler.parser.Parser. name;

//ws://127.0.0.1:8087/Demo1/ws/张三

@ServerEndpoint( "/ws")
public class WSServer {

// private String currentUser ;

private RemoteEndpoint.Basic  remote;

//连接打开时执行
@OnOpen
public void onOpen(Session session) {
remote = session.getBasicRemote();
// currentUser = user;
// System.out.println("Connected ... " + session.getId());
// try {
// remote.sendText("你有1条私信信息,请注意查收!");
// } catch (IOException e) {
// e.printStackTrace();
// }

}

//收到消息时执行
@OnMessage
public String onMessage(String message, Session session) {
System. out.println(message);
JSONObject myJsonObject = JSONObject. fromObject(message);
System. out.println(myJsonObject.getString( "userid"));
int userid = Integer. parseInt(myJsonObject.getString( "userid").toString());
int c =  ;
try {
Connection con = JDBCUntil. getConnection();
//2.创建statement类对象,用来执行SQL语句!!
Statement statement =con.createStatement();
//要执行的SQL语句
String sql =  "select  count ( * ) as rowCount from ocl_letter where isread = 0 and reciver_id ="+userid;
//3.ResultSet类,用来存放获取的结果集!!
ResultSet rs =  null;
rs = statement.executeQuery(sql);
rs.next();
c = rs.getInt( "rowCount");
// while(rs.next()){
System. out.println( "============================"+c);
// }
rs.close();
con.close();
catch (SQLException e) {
e.printStackTrace();
}
return  ""+c;

// Thread t1 = new Thread(new Runnable() {
// @Override
// public void run() {
// while(true){
// try {
// System.out.println("准备查询");
// //每隔2秒查询是否有消息
// //Thread.sleep(5000);
// System.out.println("开始查询");
// int co = letterService.selectNewLetter();
//
// if(co>0){
// //如果检测forUser-id为true,则表明有人发私信给此id用户,进而查询私信数据send给该用户
// remote.sendText("你有"+co+"条私信信息,请注意查收!");
// }
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
// });
// t1.start();
// try {
// remote.sendText("亲爱的,我收到了呢!");
// } catch (IOException e) {
// e.printStackTrace();
// }
// return currentUser + ":" + message;
}

//连接关闭时执行
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System. out.println(String. format( "Session %s closed because of %s", session.getId(), closeReason));
}

//连接错误时执行
@OnError
public void onError(Throwable t) {
t.printStackTrace();
}
}

client端:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta charset="UTF-8"/>
<title>WebSocket客户端</title>
</head>

<body>
<div>
<input type="button" id="btnConnection" value="连接" />
<input type="button" id="btnClose" value="关闭" />
<input type="button" id="btnSend" value="发送" />
</div>
<script src="js/jquery-1.10.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
//页面及数据加载完成后执行推送等socket工作
// window.οnlοad=function(){
//     //do something
//     //实现化WebSocket对象,指定要连接的服务器地址与端口
//  socket = new WebSocket("ws://127.0.0.1:8780/ocl-server/ws/987");
//  //打开事件
//  socket.onopen = function() {
//  alert("Socket 已打开");
//  //socket.send("这是来自客户端的消息" + location.href + new Date());
//  };
//  //获得消息事件
//  socket.onmessage = function(msg) {
//  alert(msg.data);
//  };
//  //关闭事件
//  socket.onclose = function() {
//  alert("Socket已关闭");
//  };
//  //发生了错误事件
//  socket.onerror = function() {
//  alert("发生了错误");
//  }
// }
$(function() {
var socket;
if(typeof(WebSocket) == "undefined") {
alert("您的浏览器不支持WebSocket");
return;
}

$("#btnConnection").click(function() {
//实现化WebSocket对象,指定要连接的服务器地址与端口
socket = new WebSocket("ws://127.0.0.1:8780/ocl-server/ws/987");
//打开事件
socket.onopen = function() {
alert("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
alert(msg.data);
};
//关闭事件
socket.onclose = function() {
alert("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("发生了错误");
}
});

$("#btnSend").click(function() {
socket.send("这是来自客户端的消息" + location.href + new Date());
});

$("#btnClose").click(function() {
socket.close();
});
});
</script>
</body>

</html>  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值