本项目实现通过UDP从终端接收数据,并通过websocket转发到手持设备的示例来演示搭建过程。websocket是基于tomcat来提供功能的,并且websocket没有添加认证策略,仅用于演示。
IDEA 2017.1.2
tomcat-8.0.43
java8
按图中所示的步骤新建maven项目:
按图中所示配置GroupId和ArtifactId:
选择maven目录:
点击Next后,在弹出的对话框点击Finish。
生成的项目目录如下:
webapp/WEB-INF/web.xml为java web环境的配置
webapp/index.jsp是默认web页,生成的是hello world。
该项目使用了spring、websocket及日志模块logback,故添加它们的依赖。
javax.websocket
javax.websocket-api
1.1
provided
org.springframework
spring-beans
4.3.10.RELEASE
org.springframework
spring-context
4.3.10.RELEASE
org.springframework
spring-web
4.3.10.RELEASE
org.springframework
spring-websocket
4.3.10.RELEASE
org.slf4j
slf4j-api
1.7.25
org.projectlombok
lombok
1.16.16
provided
ch.qos.logback
logback-classic
1.2.3
另外还需配置IDEA使用java1.8来编译(默认为java1.5),pom.xml中的build配置如下:
transformer
org.apache.maven.plugins
maven-compiler-plugin
2.3.2
1.8
项目使用SpringIoC作为容器,于是在web.xml中引入spring的配置
contextConfigLocation
/WEB-INF/spring-config.xml
org.springframework.web.context.ContextLoaderListener
配置ContextLoaderListener的作用是在启动web容器时,自动装配ApplicationContext.xml(即spring-config.xml)的配置信息并初始化spring容器。
注意context-param和listener的顺序,listener在context-param之前IDEA会提示错误。
WebSocketManager和UDPReceiver需要纳入SpringIoC中在web容器启动时创建,故它们作为java bean配置在spring-config.xml中。
spring-config.xml配置如下:
"http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
package="com.demo"/>
"wsMnager" class="com.demo.WSManager"/>
"udpReceiver" class="com.demo.UDPReceiver"/>
package com.demo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.server.standard.SpringConfigurator;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Websocket端点类.
*
* @author 东轩幽客
*
* Created on 2017/10/9.
*/
@Slf4j
@ServerEndpoint(value = "/devMessage", configurator = SpringConfigurator.class)
public class WebSocketNode {
private Session session;
private WebSocketManager manager;
@Autowired
public WebSocketNode(WebSocketManager manager) {
this.manager = manager;
}
@OnMessage
public void onMessage(String message, Session session) throws IOException, InterruptedException {
if(log.isDebugEnabled()) {
log.debug("> " + message);
}
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
log.debug("Client connected");
manager.addClient(this);
}
@OnClose
public void onClose() {
log.debug("Client closed");
manager.removeClient(this);
}
public void publish(byte[] data) throws IOException {
this.session.getBasicRemote().sendBinary(ByteBuffer.wrap(data));
}
public void publish(String data) throws IOException {
this.session.getBasicRemote().sendText(data);
}
}
注意:ServerEndpoint注解若不指定configurator,那么WebSocketNode将不会由Spring容器实例化,也就是说该类中的@Autowired注解将不生效。指定configurator为SpringConfigurator.class会将WebSocketNode的实例化纳入到Spring容器中。
WSManager类管理websocket的连接,设备的数据通过该类的publish方法发送到所有websocket客户端去。WSManager实现WebSocketManager接口。
WebSocketManager代码如下:
public interface WebSocketManager {
void addClient(WebSocketNode node);
void removeClient(WebSocketNode node);
void publish(String data);
void publish(byte[] data);
}
WSManager代码如下:
package com.demo;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.ArrayList;
/**
* websocket 客户端管理类.
*
* @author 东轩幽客
*
* Created on 2017/10/9.
*/
@Slf4j
public class WSManager implements WebSocketManager {
private ArrayList clientList;
public WSManager() {
clientList = new ArrayList();
log.info("WSManager initialized");
}
public void addClient(WebSocketNode node) {
clientList.add(node);
log.debug("new client in");
}
public void removeClient(WebSocketNode node) {
clientList.remove(node);
log.debug("client removed");
}
public void publish(String data) {
int size = clientList.size();
log.debug("send to {} clients.", size);
for (int i = 0; i < size; i++) {
try {
clientList.get(i).publish(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void publish(byte[] data) {
int size = clientList.size();
log.debug("send to {} clients.", size);
for (int i = 0; i < size; i++) {
try {
clientList.get(i).publish(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
UDPReceiver类中有一个接收UDP数据的线程,简单的实现为收到数据即调用WebSocketManager 发送到已经连接的websocket客户端中。
代码如下:
package com.demo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.net.*;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
/**
* UDP接收类.
*
* @author 东轩幽客
*
* Created on 2017/10/11.
*/
@Slf4j
public class UDPReceiver {
@Autowired
private WebSocketManager manager;
private DatagramSocket datagramSocket;
private Thread workThread;
private boolean goRun;
@PostConstruct
public void init() {
startUDPServer();
log.info("UDPReceiver initialized");
}
@PreDestroy
public void shutdown() {
stopUDPServer();
}
private void startUDPServer() {
goRun = true;
workThread = new Thread(new Runnable() {
public void run() {
try {
InetSocketAddress socketAddress = new InetSocketAddress("0.0.0.0", 7000);
System.out.println(socketAddress.toString());
datagramSocket = new DatagramSocket(socketAddress);
} catch (SocketException e) {
log.error("DatagramSocket", e);
}
byte[] buf = new byte[1024*1024];
DatagramPacket datagramPacket = new DatagramPacket(buf, 1024*1024);
while (goRun) {
try {
datagramSocket.receive(datagramPacket);
byte[] data = Arrays.copyOfRange(datagramPacket.getData(), 0, datagramPacket.getLength());
manager.publish(new String(data));
} catch (IOException e) {
log.warn("receive", e);
}
}
datagramSocket.close();
}
});
workThread.start();
}
private void stopUDPServer() {
goRun = false;
try {
workThread.join(10000);
} catch (InterruptedException e) {
log.error("udp thread join", e);
}
}
}
下面在IDEA中配置tomcat以便在IDEA中测试程序的功能。
首先确保IDEA的File->Project Structure的Facets和Artifacts的配置如下:
在java web项目创建后,这两项一般会自动生成。
然后是在Run/Debug中tomcat server,以便在IDEA中运行web容器。
点击工具栏中的:
打开Run/Debug Configurations对话框,选步骤选择:
然后按以下步骤修改名字、设置server位置:
可将On ‘Update’ action选择为Update classes and resources,减少更新时等待tomcat启动的时间。
若是第一次配置tomcat,那么Application server下拉框是空的,需要点击后面的Configure配置Tomcat Home,如下所示:
然后是配置Deployment:
选择带有exploed的Artifact:
到此,配置完毕。下面就可以开始在IDEA上运行web容器,测试程序功能了。
在工具栏点击绿色的三角按钮启动:
如无意外,在Output栏中会有如下的日志信息:
图上所示,WSManager和UDPReceiver随tomcat启动而实例化。
websocket客户端使用http://www.blue-zero.com/WebSocket。
UDP客户端使用TCP/UDP测试工具v2.1.1。
UDP工具按下图步骤启动模拟发送数据,每2秒发送一次:
然后打开websocket客户端,填写地址:ws://localhost:8080/devMessage:
可看到消息窗口中每2秒都接收到UDP客户端发送的数据。
测试完毕后,生成环境部署需要将应用打包为war,然后将war包部署到tomcat下提供服务。
打包步骤为:
执行build后生成在war在项目目录的target目录下。
将生成的transfromer.war复制到tomcat的webapps目录下。然后命令行启动tomcat。
在windows下,使用cmd切换到tomcat所在目录,这里为D:\software\apache-tomcat-8.0.43,然后执行bin\startup.bat启动tomcat:
D:\software\apache-tomcat-8.0.43>bin\startup.bat
在tomcat下的测试与IDEA中大致相同,需要注意的是,websocket的地址与IDEA运行不一样:
IDEA:ws://localhost:8080/devMessage
Tomcat:ws://localhost:8080/transformer/devMessage
部署在tomcat下运行的地址比在IDEA中多一级应用的名称,其他测试方式相同,这里不再赘述。
另外,日志的存放位置也有不同(logback配置的位置为用户目录/logs):
IDEA:在tomcat的bin目录下的logs中
Tomcat:在tomcat目录下的logs中
这里附上logback.xml配置:
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<jmxConfigurator />
<property name="log_dir" value="${user.dir}/logs/" />
<property name="maxHistory" value="30" />
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n
pattern>
encoder>
appender>
<appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERRORlevel>
<onMatch>ACCEPTonMatch>
<onMismatch>DENYonMismatch>
filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>
${log_dir}/error/%d{yyyy-MM-dd}/error-log.log
fileNamePattern>
<maxHistory>${maxHistory}maxHistory>
rollingPolicy>
<encoder>
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n
pattern>
encoder>
appender>
<appender name="WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARNlevel>
<onMatch>ACCEPTonMatch>
<onMismatch>DENYonMismatch>
filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log_dir}/warn/%d{yyyy-MM-dd}/warn-log.logfileNamePattern>
<maxHistory>${maxHistory}maxHistory>
rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%npattern>
encoder>
appender>
<appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFOlevel>
<onMatch>ACCEPTonMatch>
<onMismatch>DENYonMismatch>
filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log_dir}/info/%d{yyyy-MM-dd}/info-log.logfileNamePattern>
<maxHistory>${maxHistory}maxHistory>
rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%npattern>
encoder>
appender>
<appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUGlevel>
<onMatch>ACCEPTonMatch>
<onMismatch>DENYonMismatch>
filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log_dir}/debug/%d{yyyy-MM-dd}/debug-log.logfileNamePattern>
<maxHistory>${maxHistory}maxHistory>
rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%npattern>
encoder>
appender>
<appender name="TRACE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>TRACElevel>
<onMatch>ACCEPTonMatch>
<onMismatch>DENYonMismatch>
filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log_dir}/trace/%d{yyyy-MM-dd}/trace-log.logfileNamePattern>
<maxHistory>${maxHistory}maxHistory>
rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%npattern>
encoder>
appender>
<root>
<level value="debug" />
<appender-ref ref="console" />
<appender-ref ref="ERROR" />
<appender-ref ref="INFO" />
<appender-ref ref="WARN" />
<appender-ref ref="DEBUG" />
<appender-ref ref="TRACE" />
root>
configuration>