All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mugui.base.client.net.bagsend.WsHandle Maven / Gradle / Ivy

The newest version!
package com.mugui.base.client.net.bagsend;


import cn.hutool.core.util.URLUtil;
import com.mugui.base.base.Autowired;
import com.mugui.base.base.Component;
import com.mugui.base.client.net.baghandle.NetHandle;
import com.mugui.base.client.net.bean.NetBag;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import lombok.Getter;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

@Component
public class WsHandle {

	@Autowired
	private NetHandle handle;

	@Getter
	WebSocketClient client=null;
	public void init(String serverUrl)  {
		if(client==null){
			client=new WebSocketClient(URLUtil.toURI(serverUrl)) {
				@Override
				public void onOpen(ServerHandshake serverHandshake) {
					WsHandle.this.onOpen(serverHandshake);
				}

				@Override
				public void onMessage(String s) {
					WsHandle.this.onMessage(s);

				}

				@Override
				public void onMessage(ByteBuffer bytes) {
					WsHandle.this.onMessage(Charset.defaultCharset().decode(bytes).toString());
				}

				@Override
				public void onClose(int i, String s, boolean b) {
					WsHandle.this.onClose(i,s,b);

				}

				@Override
				public void onError(Exception e) {
					WsHandle.this.onError(e);
				}
			};
		}

	}



	public WsHandle() {
	}

	public void onOpen(ServerHandshake serverHandshake) {
		System.out.println("WebSocketListener->>onOpen");
	}

	public void onMessage(String text) {
		handle.WsHandle(NetBag.newBean(NetBag.class, text));
	}

	public void onClose(int i, String s, boolean b) {
		close();
	}

	private void close() {
		if(client!=null&&client.getSocket()!=null){
			try {
				client.getSocket().close();
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		this.client=null;
		System.out.println("WebSocketListener->>onClose");
	}

	public void onError(Exception e) {
		System.out.println("WebSocketListener->>onFailure ");
		e.printStackTrace();
		close();
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy