基于websocket-api.jar的websocket java客户端

在之前文章《基于websocket-api.jar的websocket server服务》文章中,介绍了webosocket服务端编程与html5的客户端编写。此文章则重点介绍如何在使用java编写websocket client,以方便实现websocket接口的服务间调用。

此项目源代码已经在github托管,访问地址:websocket-demo

在开发过程中发现,websocket client需要依赖运行的tomcat容器,否则无法正常接收服务器端返回的消息。所以,是通过tomcat启动时,实例化bean时调用了客户端。如果博友实现了不依赖运行中的tomcat的调用方式,还望不吝赐教。

1.maven项目配置文件(pom.xml)

<!-- tomcat websocket-api -->
<dependency>
	<groupId>javax.websocket</groupId>
	<artifactId>javax.websocket-api</artifactId>
	<scope>provided</scope>
</dependency>
<!-- tomcat websocket-api -->

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-web</artifactId>
	<version>3.2.13.RELEASE</version>
</dependency>

<!-- apache tomcat maven plugin -->
<plugin>
	<groupId>org.apache.tomcat.maven</groupId>
	<artifactId>tomcat7-maven-plugin</artifactId>
	<configuration>
		<uriEncoding>UTF-8</uriEncoding>
		<port>8080</port>
		<path>/websocket-client</path>
	</configuration>
	<!-- <dependencies> <dependency> <groupId>org.apache.tomcat</groupId> 
		<artifactId>tomcat-websocket</artifactId> <version>7.0.47</version> </dependency> 
		</dependencies> -->
</plugin>
<!-- //apache tomcat maven plugin -->

2.java web项目启动项(web.xml)

<!-- 指定spring配置文件 -->
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>
		classpath:applicationContext.xml
	</param-value>
</context-param>

<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

3.spring bean配置项(applicationContext.xml)

<bean class="com.lidetao.websocket.client.WebsocketClientTest">
	<property name="test" value="test" />
</bean>

4.websocket client java代码

WebsocketCore.java

@ClientEndpoint
public class WebsocketCore {

	/**
	 * This method level annotation can be used to decorate a Java method that
	 * wishes to be called when a new web socket session is open.<br>
	 * 
	 * <code>OnOpen</code> API:
	 * http://docs.oracle.com/javaee/7/api/javax/websocket/OnOpen.html
	 * 
	 * @param session
	 * @param config
	 */
	@OnOpen
	public void onOpen(Session session, EndpointConfig config) {
		System.out.println("client:onOpen");
	}

	/**
	 * This method level annotation can be used to make a Java method receive
	 * incoming web socket messages. <br>
	 * 
	 * <code>nMessage</code> API:
	 * http://docs.oracle.com/javaee/7/api/javax/websocket/OnMessage.html
	 * 
	 * @param message
	 * @param session
	 * 
	 */
	/*
	 * @OnMessage public void onMessage(String message, Session session) {
	 * System.out.println("client:onMessage," + message); }
	 */

	/**
	 * This method level annotation can be used to decorate a Java method that
	 * wishes to be called in order to handle errors. <br>
	 * 
	 * <code>OnError</code> API:
	 * http://docs.oracle.com/javaee/7/api/javax/websocket/OnError.html
	 * 
	 * @param session
	 * @param e
	 * 
	 */
	@OnError
	public void onError(Session session, Throwable e) {
		System.out.println("client:onError");
		e.printStackTrace();
	}

	/**
	 * This method level annotation can be used to decorate a Java method that
	 * wishes to be called when a web socket session is closing.<br>
	 * 
	 * <code>OnClose</code> API:
	 * http://docs.oracle.com/javaee/7/api/javax/websocket/OnClose.html
	 * 
	 * @param session
	 * @param cr
	 * 
	 */
	@OnClose
	public void onClose(Session session, CloseReason cr) {
		System.out.println("client:onClose");
	}

}

WebsocketClient.java

public class WebsocketClient {

	private Session session;

	public WebsocketClient(URI uri, final StringMessageHandler handler)
			throws Exception {

		if (handler == null) {
			throw new Exception("MessageHandler is null.");
		}

		/**
		 * create connection
		 */
		WebSocketContainer container = ContainerProvider
				.getWebSocketContainer();
		this.session = container.connectToServer(WebsocketCore.class, uri);

		/**
		 * set handler
		 */
		this.session.addMessageHandler(new MessageHandler.Whole<String>() {

			@Override
			public void onMessage(String message) {
				if (handler.handleWithClosed(message)) {
					try {
						session.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

		});

	}

	/**
	 * send string message
	 * 
	 * @param message
	 * @throws IOException
	 */
	public void sendMessage(String message) throws IOException {
		session.getBasicRemote().sendText(message);
	}

	public static interface StringMessageHandler {
		boolean handleWithClosed(String message);
	}

}

WebsocketClientTest.java

public class WebsocketClientTest {

	public void setTest(String test) {
		testClient();
	}

	public static void main(String[] args) {
		new WebsocketClientTest().testClient();
	}

	public void testClient() {

		URI uri = URI.create("ws://localhost:8082/websocket-server/wsApi/test");

		try {
			WebsocketClient client = new WebsocketClient(uri,
					new StringMessageHandler() {

						@Override
						public boolean handleWithClosed(String message) {
							System.out.println(message);
							return true;
						}
					});

			if (client != null) {
				client.sendMessage("hello,first websocket");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

© 2016, 李德涛博客. 版权所有.

发表评论

电子邮件地址不会被公开。 必填项已用*标注