|
@@ -0,0 +1,85 @@
|
|
|
+package com.ruoyi.system.utils;
|
|
|
+
|
|
|
+import java.io.BufferedReader;
|
|
|
+import java.io.IOException;
|
|
|
+import java.io.InputStreamReader;
|
|
|
+import java.io.PrintWriter;
|
|
|
+import java.net.InetSocketAddress;
|
|
|
+import java.net.ServerSocket;
|
|
|
+import java.net.Socket;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.concurrent.ArrayBlockingQueue;
|
|
|
+import java.util.concurrent.Executors;
|
|
|
+import java.util.concurrent.ThreadPoolExecutor;
|
|
|
+import java.util.concurrent.TimeUnit;
|
|
|
+
|
|
|
+public class SocketServer {
|
|
|
+ // socket
|
|
|
+ ServerSocket serverSocket;
|
|
|
+ Socket socket;
|
|
|
+ ThreadPoolExecutor poolExecutor;
|
|
|
+ ArrayList<Socket> sockets = new ArrayList<>();
|
|
|
+ /**
|
|
|
+ * 线程数
|
|
|
+ */
|
|
|
+ private int poolSize = 5;
|
|
|
+ /**
|
|
|
+ * 线程最大容量
|
|
|
+ */
|
|
|
+ private int maxPoolSize = 5000;
|
|
|
+ /**
|
|
|
+ * 线程等待时间
|
|
|
+ */
|
|
|
+ private int keepAliveTime = 200;
|
|
|
+ private int queueSize = maxPoolSize - poolSize;
|
|
|
+
|
|
|
+ public SocketServer() {
|
|
|
+ poolExecutor = new ThreadPoolExecutor(poolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS,
|
|
|
+ new ArrayBlockingQueue<>(queueSize), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
|
|
|
+ try {
|
|
|
+ //1、绑定端口之前应先设置相应参数,否则设置不起作用
|
|
|
+ serverSocket = new ServerSocket();
|
|
|
+ //启用端口重用
|
|
|
+ serverSocket.setReuseAddress(true);
|
|
|
+ serverSocket.bind(new InetSocketAddress(8098));
|
|
|
+ }catch(Exception e){
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public class AcceptSocket implements Runnable{
|
|
|
+ @Override
|
|
|
+ public void run() {
|
|
|
+ try {
|
|
|
+ /**
|
|
|
+ * 试试去掉while看能不能发送消息,实验证明去掉只能发送消息给第一个客户端,故不能去掉,否则创建连接时,除了第一个客户端后面的客户端将不会执行到括弧中内容,
|
|
|
+ * 但是加上之后,从服务端发送消息发送不出去了
|
|
|
+ */
|
|
|
+ while(true){
|
|
|
+ socket = serverSocket.accept();
|
|
|
+ sockets.add(socket);
|
|
|
+ System.out.println("【【【【【【【【【【创建新的连接"+ socket.getPort());
|
|
|
+ System.out.println("【【【【【【【【【【当前服务端线程数:"+poolExecutor.getPoolSize());
|
|
|
+ //接收消息
|
|
|
+ poolExecutor.execute(new ReceiveService(socket));
|
|
|
+ }
|
|
|
+ } catch (IOException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public void start(){
|
|
|
+ System.out.println("【【【【【【【【【【服务器启动....");
|
|
|
+ System.out.println("【【【【【【【【【【当前服务端线程数:"+poolExecutor.getPoolSize());
|
|
|
+ try{
|
|
|
+ poolExecutor.execute(new AcceptSocket());
|
|
|
+ }catch (Exception e){
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+// public static void main(String[] args) {
|
|
|
+// new SocketServer().start();
|
|
|
+// }
|
|
|
+}
|