默认情况下,Tomcat的WebSocket最大连接数为200。
WebSocket后台代码
package com.chat.demo;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
//import org.apache.juli.logging.Log;
//import org.apache.juli.logging.LogFactory;
//import util.HTMLFilter;
@ServerEndpoint(value = "/websocket/chat")
public class ChatAnnotation {
//private static final Log log = LogFactory.getLog(ChatAnnotation.class);
private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set<ChatAnnotation> connections =
new CopyOnWriteArraySet<ChatAnnotation>();
private final String nickname;
private Session session;
public ChatAnnotation() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
}
@OnOpen
public void start(Session session) {
this.session = session;
connections.add(this);
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
}
@OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s",
nickname, "has disconnected.");
broadcast(message);
}
@OnMessage
public void incoming(String message) {
// Never trust the client
String filteredMessage = String.format("%s: %s",
nickname, message.toString());
broadcast(filteredMessage);
}
@OnError
public void onError(Throwable t) throws Throwable {
System.out.println("Chat Error: " + t.toString());
}
private static void broadcast(String msg) {
for (ChatAnnotation client : connections) {
try {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
//log.debug("Chat Error: Failed to send message to client", e);
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
// Ignore
}
String message = String.format("* %s %s",
client.nickname, "has been disconnected.");
broadcast(message);
}
}
}
}
启动Tomcat,注意ws的地址,然后运行测试WebSocket连接数代码
package cn.idoo.getdata.controller;
import cn.idoo.getdata.Application;
import cn.idoo.getdata.MyTest;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.stream.Stream;
import static org.junit.Assert.*;
public class SocketDemoTest {
private static final Logger logger= LoggerFactory.getLogger(ReceiveRealTimeDataControllerTest.class);
private static String ws_uri = "ws://127.0.0.1:81/receiveRealTimeData";
public static WebSocketClient client;
public static void send(byte[] bytes){
client.send(bytes);
}
public static void main(String[] args) throws URISyntaxException, UnsupportedEncodingException {
client = new WebSocketClient(new URI(ws_uri),new Draft_6455()) {
@Override
public void onOpen(ServerHandshake arg0) {
System.out.println("打开链接");
}
@Override
public void onMessage(String arg0) {
logger.info("收到消息:\n"+arg0);
if(arg0.contains("数据接收成功")){
client.close();
}
}
@Override
public void onError(Exception arg0) {
arg0.printStackTrace();
System.out.println("发生错误已关闭");
}
@Override
public void onClose(int arg0, String arg1, boolean arg2) {
System.out.println("链接已关闭");
}
@Override
public void onMessage(ByteBuffer bytes) {
try {
System.out.println(new String(bytes.array(),"utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
client.connect();
while(!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)){
logger.info("wait connect!!!");
}
String msg ="hello";
logger.info("connect sucess!!!");
send(msg.getBytes("utf-8"));
client.send(msg);
}
}
运行结果为每次循环到第200个的时候,测试结束了,WebSocket后台代码开始报错。
如何增加并发数呢,只需在server.xml文件中,增加 maxThreads="300" 这样最大的并发数就变成了300。
<Connector maxConnections="300" maxThreads="300" URIEncoding="UTF-8" connectionTimeout="20000" port="8028" protocol="HTTP/1.1" redirectPort="8443" useBodyEncodingForURI="true"/>
https://blog.csdn.net/qq_28859405/article/details/73656920
WebSocket 在线测试工具:https://www.easyswoole.com/wstool.html