Java WebSocket客户端java WebSocketClient

一、java客户端实现代码

package ggmes.websocket.client;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;

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

public class MsgWebSocketClient extends WebSocketClient{

	public MsgWebSocketClient(String url) throws URISyntaxException {
		super(new URI(url));
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onOpen(ServerHandshake shake) {
		// TODO Auto-generated method stub
		System.out.println("握手...");
		for(Iterator it=shake.iterateHttpFields();it.hasNext();) {
			String key = it.next();
			System.out.println(key+":"+shake.getFieldValue(key));
		}
	}

	@Override
	public void onMessage(String paramString) {
		// TODO Auto-generated method stub
		System.out.println("接收到消息:"+paramString);
	}

	@Override
	public void onClose(int paramInt, String paramString, boolean paramBoolean) {
		// TODO Auto-generated method stub
		System.out.println("关闭...");
	}

	@Override
	public void onError(Exception e) {
		// TODO Auto-generated method stub
		System.out.println("异常"+e);
		
	}
}

二、单例初始化类:

package ggmes.websocket.pusher;

import java.net.URI;
import java.net.URISyntaxException;

import ggmes.websocket.client.MsgWebSocketClient;
import ggmes.websocket.server.MsgWebSocketServer;
import utils.ObjectUtils;

public enum WebClientEnum {

	CLIENT;
	
	private static MsgWebSocketClient socketClient = null;
	
	public static void initClient(MsgWebSocketClient client) {
		socketClient = client;
		if(ObjectUtils.isNotNull(socketClient)) {
			socketClient.connect();
			socketClient.send("测试websocket。。。");
		}
		boolean flag = true;
		int i=1000;
		while(flag) {
			socketClient.send("测试websocket。。。"+(i--));
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(i == 0) {
				flag = false;
			}
		}
	}
	
}

三、启动主方法:

package ggmes.websocket.bootstrap;


import java.net.InetSocketAddress;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import ggmes.websocket.client.MsgWebSocketClient;
import ggmes.websocket.pusher.WebClientEnum;
import ggmes.websocket.pusher.WebServerEnum;
import ggmes.websocket.server.MsgWebSocketServer;
import play.mvc.Controller;

public class SocketClientEngine{


	public static void main(String[] args) {
		try {
			WebClientEnum.CLIENT.initClient(new MsgWebSocketClient("ws://192.168.152.73:8099"));
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(java,java,后端)