Java实现多websocket客户端压测

pom中引入:

        <dependency>
			<groupId>org.java-websocket</groupId>
			<artifactId>Java-WebSocket</artifactId>
			<version>1.4.0</version>
		</dependency>

测试代码:

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

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

public class TestWebsocketClient {

	public static void main(String[] args) throws Exception {
		String url = "ws://192.168.1.154:8445";
		for (int i = 0; i < 20; i++) {
			MyWebsocketClient myclient = new MyWebsocketClient();
			myclient.startConn(url, i);
			Thread.sleep(50);
		}

	}

}

class MyWebsocketClient {

	public WebSocketClient client;

	public void startConn(String url, final int i) {
		try {
			client = new WebSocketClient(new URI(url), new Draft_6455()) {
				@Override
				public void onOpen(ServerHandshake serverHandshake) {
					System.out.println("connect ok  >>> " + i);
					client.send("admin:123456");
				}

				@Override
				public void onMessage(String msg) {
//                    System.out.println("收到消息=========="+msg);
					if (msg.equals("over")) {
						client.close();
					}
				}

				@Override
				public void onClose(int i, String s, boolean b) {
					System.out.println("connect close");
				}

				@Override
				public void onError(Exception e) {
					e.printStackTrace();
					System.out.println("connect error");
				}
			};
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}

		client.connect();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				System.out.println("send alive by  >>> " + i);
//				while(true) {
//					
//					client.send("alive:alive");
//					try {
//						Thread.sleep(10);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//				}
				for (int j = 0; j < 10000; j++) {
					client.send("alive:alive");
					System.out.println("send alive by  >>> " + i + " times >>> "+ j);
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				System.out.println("send alive over  >>> " + i);
			}
		});
		t1.start();

	}

}


测试工具:

不同端口在同时发送数据,告辞! 

猜你喜欢

转载自blog.csdn.net/qq_21454973/article/details/125560383