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() {
		//写出自己定时器操作的代码
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值