websocket 简单用例

maven项目 pom.xml

注意: 里面的两个包 websocket-api 与 tomcat7-websocket  是我从Tomcat7的lib下面拷贝到,自己本地Maven私服里面的. 


<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>socket</groupId>
	<artifactId>websocket</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.3</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.4</version>
		</dependency>
		<dependency>
			<groupId>com.websocket</groupId>
			<artifactId>websocket-api</artifactId>
			<version>1.0</version>
		</dependency>
		<dependency>
			<groupId>com.websocket</groupId>
			<artifactId>tomcat7-websocket</artifactId>
			<version>1.0</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>${project.name}</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<uriEncoding>UTF-8</uriEncoding>
					<port>8080</port>
					<path>/</path>
					<!-- 应用的部署位置 -->
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>



java文件  ChatServer.java


package com.zlx.websocket.server;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSONObject;

/**
 * 聊天服务器类
 * 
 * @ClassName: ChatServer
 * @Description: websocket 聊天服务器
 * @author Zlx
 * @date 2015-6-26 上午11:12:31
 * @version V1.0
 */
@ServerEndpoint("/socket")
public class ChatServer {
	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm"); // 日期格式化

	@OnOpen
	public void open(Session session) {
		// 添加初始化操作
	}

	/**
	 * 接受客户端的消息,并把消息发送给所有连接的会话
	 * 
	 * @param message
	 *            客户端发来的消息
	 * @param session
	 *            客户端的会话
	 */
	@OnMessage
	public void getMessage(String message, Session session) {
		// 把客户端的消息解析为JSON对象
		JSONObject jsonObject = JSONObject.parseObject(message);
		// 在消息中添加发送日期
		jsonObject.put("date", DATE_FORMAT.format(new Date()));
		// 把消息发送给所有连接的会话
		for (Session openSession : session.getOpenSessions()) {
			// 添加本条消息是否为当前会话本身发的标志
			jsonObject.put("isSelf", openSession.equals(session));
			// 发送JSON格式的消息
			openSession.getAsyncRemote().sendText(jsonObject.toString());
		}
	}

	@OnClose
	public void close() {
		// 添加关闭会话时的操作
	}

	@OnError
	public void error(Throwable t) {
		// 添加处理错误的操作
	}
}



jsp文件  index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>chat</title>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<meta name="renderer" content="webkit">
<meta http-equiv="Cache-Control" content="no-siteapp" />

</head>
<body>
	<div style="width: 500px;height: 200px;">
		<ul id="message-list" ></ul>
	</div>
	<div>
		<textarea rows="20" cols="80" id="myEditor" ></textarea>
	</div>
	<div>
		<input id="nickname" type="text" class="am-form-field" placeholder="Please enter nickname"/>
		<button id="send" type="button"  >Send</button>
	</div>
	
	<script>
		$(function() {
			// 初始化消息输入框
			//var um = UM.getEditor('myEditor');
			var um =$('#myEditor');
			// 使昵称框获取焦点
			$('#nickname')[0].focus();
			// 新建WebSocket对象,最后的/WebSocket跟服务器端的@ServerEndpoint("/websocket")对应
			var socket = new WebSocket('ws://${pageContext.request.getServerName()}:${pageContext.request.getServerPort()}${pageContext.request.contextPath}/socket');
			// 处理服务器端发送的数据
			socket.onmessage = function(event) {
				addMessage(event.data);
			};
			// 点击Send按钮时的操作
			$('#send').on('click', function() {
				var nickname = $('#nickname').val();
				var msg = um.val();
				if ($.trim(msg) =="") {	// 判断消息输入框是否为空
					// 消息输入框获取焦点
					um.focus();
				} else if (nickname == '') {	// 判断昵称框是否为空
					//昵称框获取焦点
					$('#nickname')[0].focus();
				} else {
					// 发送消息
					socket.send(JSON.stringify({
						content : msg,
						nickname : nickname
					}));
					// 清空消息输入框
					um.val('');
					// 消息输入框获取焦点
					um.focus();
				}
			});

			// 把消息添加到聊天内容中
			function addMessage(message) {
				message = JSON.parse(message);
				var messageItem = '<li> '
						+ message.nickname + '  ' + message.date
						+ '<br/>'
						+ '' + message.content
						+ '</li>';
				$(messageItem).appendTo('#message-list');
			}
		});
	</script>
</body>
</html>



已标记关键词 清除标记
表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符 “速评一下”
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页