创建一个web项目

导入依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.chu</groupId>
<artifactId>webSocket</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging> <dependencies>
<!-- servlet-api-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- websocket-api-->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<!-- 设置作用域 默认compile 编译 测试 运行
provided 编译 测试
runtime 测试 运行
test 测试-->
<scope>provided</scope>
</dependency>
<!-- JSON转换-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
</dependencies> <!-- <build>-->
<!-- <plugins>-->
<!-- maven自带的tomcat插件 需要配置对应的命令 tomcat7:run-->
<!-- <plugin>-->
<!-- <groupId>org.apache.tomcat.maven</groupId>-->
<!-- <artifactId>tomcat7-maven-plugin</artifactId>-->
<!-- <version>2.2</version>-->
<!-- <configuration>-->
<!-- <port>80</port>-->
<!-- <path>/</path>-->
<!-- <uriEncoding>UTF-8</uriEncoding>-->
<!-- </configuration>-->
<!-- </plugin>-->
<!-- </plugins>-->
<!-- </build>--> </project>

controller层代码:

package com.chu.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/*
小楚想要发送信息给小赵
这个信息会先存储在服务器
再由服务器发送给小赵
*/
@ServerEndpoint("/chat/{name}")
public class ChatSocket { //定义一个Map集合,用来存放登陆到服务器的客户名称和Session
private static Map<String,Session> mapMessage = new HashMap<>(); //首先,方法名称可以自定义
// *形参---name---Session
@OnOpen//会话开始
public void onOpen(@PathParam("name")String name, Session session){
System.out.println("onOpen....."+name);
//key-----name value-----session
mapMessage.put(name,session); }
//客户机信息处理 * 形参---Session session ---String message
@OnMessage
public void onMessage(Session session,String message){
System.out.println("onMessage....."+message);
//服务端给客户端发消息,走的不是HTTP 而是直接推送过去了
//获取JSON对象
ObjectMapper mapper = new ObjectMapper();
try {
//获取JSON格式的信息
Map<String,String> map = mapper.readValue(message, Map.class);
//获取需要发送的信息:content
String content = map.get("content");
//获取接收信息者:小赵
String receive = map.get("receive");
//从事先定义好的Map中获取小赵的Session
Session receiveSession = mapMessage.get(receive);
//如果小赵的Session为null
if(receiveSession==null){
//响应:对方不在线
session.getAsyncRemote().sendText("对方不在线");
}else{
//否则将接收到的信息发送给小赵
receiveSession.getAsyncRemote().sendText(content);
}
} catch (IOException e) {
e.printStackTrace();
} }
//会话结束
@OnClose
public void onClose(Session session){
System.out.println("onClose....."+session);
}
//会话出现异常
@OnError
public void onError(Session session,Throwable e){
try {
e.printStackTrace();
session.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

jsp代码:

 <body>
<div align="center" style="padding-top: 50px"> 发送者<input id="sendOut"><br> 接收者<input id="receive"><br> 信息<input id="content"><br> <input type="button" value="注册" onclick="reg()"> <input type="button" value="提交" onclick="sendmsg()"><br> <span id="list"></span> <script type="text/javascript">
var ws;
// 注册按钮
function reg() {
// 注册路径 加上自己的用户名
ws = new WebSocket("ws://localhost:8080/chat/"+document.getElementById("sendOut").value)
//接收服务器信息并显示
ws.onmessage = function (msg) {
//接收服务器信息
var message = msg.data
//获取展示信息的位置
var former = document.getElementById("list")
former.innerHTML=former.innerHTML+"...他说"+message
}
}
function sendmsg() {
// 获取接收者
var receive = document.getElementById("receive").value
//获取发送的内容
var content = document.getElementById("content").value
//以JSON的方式发送到服务器
ws.send('{"receive":"'+receive+'","content":"'+content+'"}')
//获取展示信息的位置
var former = document.getElementById("list")
former.innerHTML=former.innerHTML+"...你说"+content
}
</script>
</div>
</body>

WebSocket的简单实现&jsp的更多相关文章

  1. 最简单的jsp+servlet的增删改查代码

    package ceet.ac.cn.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.s ...

  2. [异常解决] 初玩SAE遇到的小问题——注册&创建项目+MyEclipse装插件直接部署+一个简单的JSP部署实现

    ① 新浪SAE快速上手教程:http://jingyan.baidu.com/season/43090 上面一个链接是针对PHP的相关介绍,如果用java还有点不一样,具体请看新浪SAE官网:http ...

  3. 一个简单的jsp自定义标签

    学到了一个简单的jsp自定义标签,后面有更多的例子,会更新出来: 例子1: 步骤: 1.编写标签实现类: 继承javax.servlet.jsp.tagext.SimpleTagSupport; 重写 ...

  4. OpenCms JSP 模板开发——创建一个简单的JSP模板

    OpenCms中的JSP模板就是一个普通的JSP页面,在特定的位置使用标签来包含内容,在这个的例子中,我们将要开发一个简单JSP模板,这个模板只是在内容(如<html>.<body& ...

  5. 一个简单的JSP程序示例

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"% ...

  6. 不通过ecplise,只通过文件目录 创建最简单的JSP文件

    手动创建最简单的JSP 文件   1.在Tomcat 6.0的安装目录的webapps目录下新建一个目录,起名叫myapp. 2.在myapp目录下新建一个目录WEB-INF,注意,目录名称是区分大小 ...

  7. nodejs与websocket模拟简单的聊天室

    nodejs与websocket模拟简单的聊天室 server.js const http = require('http') const fs = require('fs') var userip ...

  8. websocket(二)--简单实现网页版群聊

    websocket可以实现服务端的消息推送,而不必在客户端轮询,大大的节省的资源,对于实时通讯来说简直是个大喜讯. 在上一篇文章中介绍了协议握手,这篇文章将通过实现简单的群聊来帮助进一步了解webso ...

  9. websocket实现简单聊天程序

    程序的流程图: 主要代码: 服务端 app.js 先加载所需要的通信模块: var express = require('express'); var app = express(); var htt ...

随机推荐

  1. 微信小程序—页面跳转

    问题: 实现页面跳转:index页面通过按钮跳转到next页面 方法: 1.页面index.wxml增加一个按钮 // index.wxml <button bindtap="jump ...

  2. 单选与多选与label

    单选radio和多选checkbox是用name属性关联的 相同的name就相当于同一道题 <input type="radio" name="radio" ...

  3. 019、Java中定义字符

    01.代码如下: package TIANPAN; /** * 此处为文档注释 * * @author 田攀 微信382477247 */ public class TestDemo { public ...

  4. oracle通用帮助类

    需要的dll( EntityFramework.6.0.0Oracle.ManagedDataAccess.12.1.2400System.Configuration.dllEmitMapper.1. ...

  5. C++连接sqlite数据库的坑

    新的第一次用vs2013搞 C++连接sqlite数据库,遇到了很多问题,我也不搞不懂~~~下面写点小体会 首先: 你要先配置好sqlite的环境 参考链接: https://blog.csdn.ne ...

  6. NAND Flash驱动

    硬件原理及分析 管脚说明         Pin Name Pin Function R/B(RnB) The R/B output indicates the status of the devic ...

  7. word中替换内容

    参考了一篇文章 然后做了如下修改  用python的win32com模块替换word中的文字搞定批量打印奖状 python 操作 office python操作word # -*- coding: u ...

  8. C# 并行线程调用

    参考 一.异步委托开启线程 Action<int, int> a = add; a.BeginInvoke(, , null, null);//前两个是add方法的参数,后两个可以为空 C ...

  9. Java 二叉树深度 判断平衡二叉树

    package cookie; public class BTreeDepthIsBalanced { int depth(BNode head) { if (head == null) { retu ...

  10. Bean 注解(Annotation)配置(3)- 依赖注入配置

    Spring 系列教程 Spring 框架介绍 Spring 框架模块 Spring开发环境搭建(Eclipse) 创建一个简单的Spring应用 Spring 控制反转容器(Inversion of ...