欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

websocket,使用tomcat7转发

程序员文章站 2024-03-23 10:48:52
...
前篇:
[url]http://haoningabc.iteye.com/blog/2011985[/url]
代码的git地址
[url]https://github.com/killinux/mysocket/tree/master/websocket/project/tomcat7servlet[/url]


如果是使用tomcat7的模式
1.html是客户端
2.tomcat7的servlet对websocket协议进行了封装,里面转发给普通的socket服务端
3.普通的socket 作为服务端


html ----->tomcat7,servlet----->socket server


这里纯js的客户端:

<!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.0.102:5000";
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>


如果是用java-websocket,

git为 https://github.com/killinux/Java-WebSocket
代码如下:
socket server端:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
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());
}
}

}

}

----------------------------------------------------------------------
----------------------------------------------------------------------
[b]如果server是用tomcat转发[/b]
参考
http://blog.csdn.net/a79412906/article/details/9393515
servlet:

package com.hao;

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 javax.servlet.http.HttpServletRequest;

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,HttpServletRequest arg1) {

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.102", 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);
}
};
}

public static void main(String[] args) {
Socket socket;
String message ="haoning";
String msg = "";
try {
// 向服务器利用Socket发送信息
socket = new Socket("192.168.0.102", 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();
}
}
}


web.xml配置:

<servlet>
<servlet-name>wsSnake</servlet-name>
<servlet-class>com.hao.HelloWorldWebSocketServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>wsSnake</servlet-name>
<url-pattern>/websocket/test</url-pattern>
</servlet-mapping>

tomcat7的
配置

<?xml version='1.0' encoding='utf-8'?>
<Context crossContext="true" docBase="D:/workspace/work1/Test/webapp" path="/webs" reloadable="true">
</Context>

中心server代码:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
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();
System.out.println("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());
}
}

}

}


客户端改进如下:

<!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 log(text) {
document.getElementById("log").innerHTML = (new Date).getTime() + ": " + text +"<br>"+ document.getElementById("log").innerHTML;
}
function startServer() {
var url = document.getElementById("serverip").value;// "ws://192.168.0.102:8887";
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);
log('Receive message: ' + event.data);
};
ws.onclose = function() {
alert('Closed!');
}
document.getElementById("conbtn").disabled="true";
document.getElementById("stopbtn").removeAttribute('disabled');
}
//发送信息
function sendMessage(){
var textMessage=document.getElementById("textMessage").value;

if(ws!=null&&textMessage!=""){
ws.send(textMessage);

}
}
function stopconn(){
ws.close();
document.getElementById("conbtn").removeAttribute('disabled');
document.getElementById("stopbtn").disabled="true";
}
</script>
<body onload="">
<input id="serverip" type="text" size="20" value="ws://192.168.0.102:8887"/>
<input id="conbtn" type="button" onclick="startServer()" value="open" />
<input id="stopbtn" type="button" onclick="stopconn()" value="stop" disabled="disabled"/>
</br>
<input id="textMessage" type="text" size="20" />
<input type="button" onclick="sendMessage()" value="Send">
<div id="log"></div>
</body>
</html>



servlet中发现,不能广播,只能单纯的返回,如果想每个浏览器都受到消息,则修改如下

package com.hao;

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 java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;

public class HelloWorldWebSocketServlet extends WebSocketServlet {
private static ArrayList mmiList = new ArrayList();

protected StreamInbound createWebSocketInbound(String subProtocol,
HttpServletRequest arg1) {
return new MyMessageInbound();
}

private class MyMessageInbound extends MessageInbound {
WsOutbound myoutbound;

@Override
public void onOpen(WsOutbound outbound) {
try {
System.out.println("Open Client.");
this.myoutbound = outbound;
mmiList .add(this);
outbound.writeTextMessage(CharBuffer.wrap("Hello!"));
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public void onClose(int status) {
System.out.println("Close Client.");
mmiList .remove(this);
}

@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());
for (int i=0;i< mmiList.size();i++ ) {
MyMessageInbound mmib = (MyMessageInbound) mmiList.get(i);
CharBuffer buffer = CharBuffer.wrap(message);
mmib.myoutbound.writeTextMessage(buffer);
mmib.myoutbound.flush();
}

/*Socket socket;
String msg = "";
try {
// 向服务器利用Socket发送信息
socket = new Socket("192.168.0.102", 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);*/
}
}

public static void main(String[] args) {
Socket socket;
String message = "haoning";
String msg = "";
try {
// 向服务器利用Socket发送信息
socket = new Socket("192.168.0.102", 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();
}
}
}


这段参考
http://blog.fens.me/java-websocket-intro/
相关标签: websocket