package com.example.agvcontroller.socket; import android.util.Log; import java.io.Serializable; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; public class SocketManager { private Thread serverThread; private NettyServer nettyServer; private boolean isRunning = false; public void startServer(final int port) { if (isRunning) return; isRunning = true; serverThread = new Thread(new Runnable() { @Override public void run() { try { nettyServer = new NettyServer(port); nettyServer.start(); } catch (InterruptedException e) { e.printStackTrace(); } } }); serverThread.start(); } public void stopServer() { if (!isRunning) return; isRunning = false; if (nettyServer != null) { nettyServer.stop(); } if (serverThread != null && serverThread.isAlive()) { serverThread.interrupt(); } } public void sendMessage(String clientId, byte[] message) { Log.i("Socket Manager",clientId); NettyServerHandler.sendMessageToClient(clientId, message); } //private static SocketManager instance; //private Channel channel; //private EventLoopGroup bossGroup; //private EventLoopGroup workerGroup; //private int port; // //private SocketManager() { // bossGroup = new NioEventLoopGroup(1); // 主线程池,用于接受客户端连接 // workerGroup = new NioEventLoopGroup(); // 工作线程池,用于处理客户端请求 //} // //public static synchronized SocketManager getInstance() { // if (instance == null) { // instance = new SocketManager(); // } // return instance; //} // //public void setPort(int port) { // this.port = port; //} // //public void startServer() { // ServerBootstrap serverBootstrap = new ServerBootstrap(); // serverBootstrap.group(bossGroup, workerGroup) // .channel(NioServerSocketChannel.class) // .childHandler(new ChannelInitializer() { // @Override // protected void initChannel(SocketChannel ch) throws Exception { // ch.pipeline().addLast(new NettyServerHandler()); // } // }); // // try { // channel = serverBootstrap.bind(port).sync().channel(); // System.out.println("Server started on port " + port); // } catch (InterruptedException e) { // e.printStackTrace(); // } //} // //public void stopServer() { // if (channel != null) { // channel.close(); // } // bossGroup.shutdownGracefully(); // workerGroup.shutdownGracefully(); // System.out.println("Server stopped"); //} }