Tomcat7支持WebSocket
jopen
11年前
今天研究了一下tomcat7的websocket,首先我们看看chrome浏览器的支持的js代码,html5支持websocket
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!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=utf-8"> <title>Insert title here</title> </head> <script type="text/javascript"> var ws = null; function startServer() { var url = "ws://192.168.1.109/websocket/helloWorld"; if ('WebSocket' in window) { ws = new WebSocket(url); } else if ('MozWebSocket' in window) { ws = new MozWebSocket(url); } else { alert('浏览器不支持'); return; } ws.onopen = function() { //alert('Opened!'); }; // 收到服务器发送的文本消息, event.data表示文本内容 ws.onmessage = function(event) { alert('Receive message: ' + event.data); }; ws.onclose = function() { // alert('Closed!'); } } //发送信息 function sendMessage(){ var textMessage=document.getElementById("textMessage").value; if(ws!=null&&textMessage!=""){ ws.send(textMessage); } } </script> <body onload="startServer()"> <input type="text" id="textMessage" size="20" /> <input type="button" onclick="sendMessage()" value="Send"> </body> </html>
上面主要是JS的代码,主要是浏览器发送socket给tomcat7,和结束tomcat返回的信息
在web项目中,我们要建一个servlet
package com.auscend.servlet; import java.io.DataInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import org.apache.catalina.websocket.MessageInbound; import org.apache.catalina.websocket.StreamInbound; import org.apache.catalina.websocket.WebSocketServlet; public class HelloWorldWebSocketServlet extends WebSocketServlet{ protected StreamInbound createWebSocketInbound(String subProtocol){ return new MessageInbound() { @Override protected void onBinaryMessage(ByteBuffer arg0) throws IOException { // TODO Auto-generated method stub } @Override protected void onTextMessage(CharBuffer message) throws IOException { // TODO Auto-generated method stub System.out.println("onText--->"+message.toString()); Socket socket; String msg = ""; try { //向服务器利用Socket发送信息 socket = new Socket("192.168.1.109", 5000); // socket = new Socket("127.0.0.1",5000); PrintWriter output = new PrintWriter(socket.getOutputStream()); output.write(message.toString()); output.flush(); //这里是接收到Server的信息 DataInputStream input = new DataInputStream(socket.getInputStream()); byte[] b = new byte[1024]; input.read(b); //Server返回的信息 msg = new String(b).trim(); output.close(); input.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //往浏览器发送信息 CharBuffer cb = CharBuffer.wrap(new StringBuilder(msg)); getWsOutbound().writeTextMessage(cb); }};}}
下面是Server,相当于中央机
public class Server { /** 端口号 */ public static final int PORT = 5000; public static void main(String[] args) { System.out.println("服务器...\n"); Server ser = new Server(); ser.sock(); } public void sock() { try { ServerSocket server = new ServerSocket(PORT); while (true) { // 一旦有堵塞, 则表示服务器与客户端获得了连接 Socket client = server.accept(); // 处理这次连接 new PServer(client); } } catch (Exception e) { System.out.println("服务器异常: " + e.getMessage()); } } private class PServer implements Runnable { private Socket socket; public PServer(Socket sock) { socket = sock; new Thread(this).start(); } public void run() { System.out.println("一个客户端连接ip:" + socket.getInetAddress()); try { // 读取客户端数据 DataInputStream input = new DataInputStream( socket.getInputStream()); // 向客户端发送数据 DataOutputStream out = new DataOutputStream( socket.getOutputStream()); // 读取客户端数据 // System.out.println("客户端发过来的内容: " + input.readUTF()); byte[] bt = new byte[1024]; int leng = input.read(bt); System.out.println(new String(bt, 0, leng)); // 发送键盘输入的一行 // String s = new BufferedReader(new // InputStreamReader(System.in)).readLine(); String s = "server d shu ru"; out.write(s.getBytes()); out.flush(); input.close(); out.close(); socket.close(); } catch (Exception e) { System.out.println("服务器 run 异常: " + e.getMessage()); } } } }
这里的tomcat是使用的tomcat7.0.28,其他版本方法有点改动,好像是加了一个request的参数。
来自:http://blog.csdn.net/a79412906/article/details/9393515