WebSocket Learn to sharing
来源:互联网 发布:mac声音被锁 编辑:程序博客网 时间:2024/06/06 19:56
用WebSocket、JavaScript、服务端是jetty7开发的网页版聊天室和以java版的聊天室。
首先介绍一个特别好用的eclipse支持jetty的插件。为run-jetty-run插件,可以在Eclipse help->Eclipse Marketplace 进入以后,可以搜索run-jetty-run,选择install安装后,可以看到在Run Configuration中看到Jetty Webapp.至此插件安装成功,在项目上或者项目任何一个文件点右键就会出现Run as->Run Jetty.这个插件的好处是热部署,不需要将web应用程序打成war包进行发布,可以将jetty直接嵌入到web application中。
===============================================服务器安装好的分割线==========================================
接下来就需要web应用程序运行jar的包。可以在官网上进行下载jetty各个版本的jar文件,在这里贴一个【jetty-all-7.6.2.v20120308.jar】,里面就有jetty-websocket.jar包。
同时需要servlet-api-2.5.jar包。
这是WebSocket在javascript api 的实现方式,以下是客户端代码:
WebSocket API在javascript中有以下事件。
onopen: 在成功建立连接时触发
onclose:关闭连接时触发
onerror: 在发生错误时触发,连接不能持续
onmessage:在收到服务器发送来的message时触发
当客户端在连接建立以后可以发送消息给服务端,send方法。
首先创建了一个websocket对象,用于尝试连接到远端地址,如果连接成功,就会触发onopen事件。
客户端WebSocket 实现:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><%String ctx = request.getContextPath();%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>WebSocket:chat</title><script type="text/javascript" src="<%=ctx%>/scripts/jquery-1.7.2.min.js"></script><script type="text/javascript"> var ws; $(document).ready(function(){ ws = new WebSocket("ws://localhost:8080/example/chat"); ws.onmessage = function(event){ var $textarea = $('#messages'); $textarea.val($textarea.val()+event.data+"\n"); $textarea.animate({scrollTop:$textarea.height},1000); }; ws.onopen=function(){$('#status').text("The Chat Connection is open.");}; ws.onclose=function(){$('#status').text("The Chat Connection has been closed.");}; }); function sendMessage(){ var data = $('#username').val()+": "+$('#msg').val(); ws.send(data); $('#msg').val(''); }</script></head><body> <h1>WebSocket:Chat</h1> <div id="status"></div><br/> username:<input id="username" value="" /><br/> <textarea id="messages" rows="20" cols="60" readonly="readonly"></textarea><br/> <input id="msg" type="text" /> <input type="button" value="send" onclick="sendMessage();" /></body></html>
启动两个浏览器分别输入消息在textarea区域就可以看到其他人输入的消息。
服务器端WebSocket实现:
import java.io.IOException;import java.util.Set;import java.util.concurrent.CopyOnWriteArraySet;import javax.servlet.http.HttpServletRequest;import org.eclipse.jetty.websocket.WebSocket;import org.eclipse.jetty.websocket.WebSocketServlet;public class ChatServlet extends WebSocketServlet{ private final Set<ChatWebSocket> members = new CopyOnWriteArraySet<ChatWebSocket>(); @Override public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) { return new ChatWebSocket(); } class ChatWebSocket implements WebSocket.OnTextMessage{ private Connection connection; @Override public void onClose(int statusCode, String reason) { members.remove(this); } @Override public void onOpen(Connection conn) { this.connection = conn; members.add(this); } @Override public void onMessage(String msg) { try { for(ChatWebSocket socket:members){ socket.connection.sendMessage(msg); } } catch (IOException e) { e.printStackTrace(); } } }}至此一个网页版的聊天室就建立好啦。。。。有木有很简单呀
Jetty对WebSocket客户端实现。贴代码 :
WebSocketClientFactory factory = new WebSocketClientFactory(); factory.start(); WebSocketClient client = factory.newWebSocketClient(); ClientWebSocket socket = new ClientWebSocket(); socket.setName(getClientName()); WebSocket.Connection connection = client.open( new URI("ws://localhost:8080/example/chat"), socket).get(); connection.setMaxIdleTime(60 * 30 * 1000);服务端同以上js 服务器端处理类似。
在GrepCode上可以研究源码。
- WebSocket Learn to sharing
- Sharing with Git,Learn how to use Git to share your Xcode projects
- learn how to learn
- learn how to learn
- To Learn
- To learn, to share.
- Learn to fail or fail to learn.
- knowledge need to learn
- How to learn c++
- Knowledge to learn
- How to learn Japanese ?
- How to learn C++
- Recently Need to learn
- Begin to learn python
- How to learn English
- How to learn XI
- begin to learn crake
- good place to learn
- crtmpserver流媒体服务器的介绍与搭建
- sysbench安装
- 《一炮走红的国家》:探寻新兴国家的经济奇迹
- 博客收集贴
- 《调试九法:软硬件错误的排查之道》学习笔记
- WebSocket Learn to sharing
- weblogic web core
- iOS开发之---静态库的编译以及相关问题的处理
- Mac OS X 安装 nginx + php fcgi
- Erlang open_port极度影响性能的因素
- Django 的 CSRF 保护机制
- Git 基础知识
- NYOJ 673 悟空的难题
- 求祝福