websocket的java客户端,使用Tomcat中的websocket搭建

pom.xml的配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>

客户端的写作:

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Timer;
import java.util.TimerTask;

import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ClientEndpoint
public class SocketClient{

	public static Session session;
	public static boolean CLOSED = false;
	private final static Logger LOG = LoggerFactory.getLogger(SocketClient.class);
	static Timer timer = null;
	static Mytask timerTask = null;
	
	@OnOpen
	public void onOpen(Session session1) {
		session = session1;
		heart();
	}
	
	@OnMessage
	public void onMessage(String msg) {
		LOG.info(msg);
		new DealMsg().dealMsg(msg);
	}
	
	@OnError
	public void onError(Throwable t) {
		LOG.info("连接错误的断开");
		t.printStackTrace();
		try {
			connection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@OnClose
	public void onClose() {
		LOG.info("连接服务器关闭");
		CLOSED = true;
	}
	
	public static void send(String message){
		if (session.isOpen()) {
			LOG.info("send:" + message);
			session.getAsyncRemote().sendText(message);			
		}
    }
	
	public static void close() {
		if (session != null) {
			try {
				session.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void connection() throws DeploymentException, IOException, URISyntaxException {
		WebSocketContainer container = ContainerProvider.getWebSocketContainer(); // 获取WebSocket连接器,其中具体实现可以参照websocket-api.jar的源码,Class.forName("org.apache.tomcat.websocket.WsWebSocketContainer");
		String uri = "连接的服务器地址";
		SocketClient sc = new SocketClient();
		container.connectToServer(sc, new URI(uri));
		CLOSED = false;
	}
	
	// 心跳,每55秒发送一次
	public void heart() {
		timer = new Timer(true);
		timerTask = new Mytask();
		timer.scheduleAtFixedRate(timerTask, 55000, 55000);
	}
	
	// 重置心跳
	public void resetHeart() {
		if (timer != null) {
			if (timerTask != null) {
				timerTask.cancel();
			}
			timerTask = new Mytask();
			timer.scheduleAtFixedRate(timerTask, 0, 55000);
		}
	}
}

class Mytask extends TimerTask {

	@Override
	public void run() {
		//写出自己定时器操作的代码
	}
	
}

猜你喜欢

转载自blog.csdn.net/ademing/article/details/82178673