一般在啟動類上添加
注意:一般檢測TCP傳輸的數據軟件----Sockit
@SpringBootApplication public class Application extends SpringBootServletInitializer implements CommandLineRunner { @Autowired //注意此處將要用的TCP進行調用 TcpSocketServer tcpSocketServer;
public static void main(String[] args)throws IOException { SpringApplication.run(Application.class, args); } @Override //重寫run方法,來對TCP數據進行操作 public void run(String... args) throws Exception { tcpSocketServer.startSocketServer(port); //注:此處port綁定端口號 } }
在 tcpSocketServer 內: 注意:一般涉及TCP接口的項目都是關於指令上傳和下發的
@Component
@Slf4j //前提是 導入了lombok的包
public class TcpSocketServer extends BaseController {
@Autowired
TcpServices tcpServices;
@Autowired
XxxService xxxService;
private Charset cs = Charset.forName("UTF-8");
//接受數據緩沖區
private static ByteBuffer sBuffer = ByteBuffer.allocate(1024);
//發送數據緩沖區
private static ByteBuffer rBuffer = ByteBuffer.allocate(1024);
//監聽器
private static Selector selector;
private static String responseMsg;
/**
* 啟動socket服務,開啟監聽
*
* @param port
* @throws IOException
*/
public void startSocketServer(int port) {
try {
//打開通信信道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//設置為非阻塞
serverSocketChannel.configureBlocking(false);
//獲取套接字
ServerSocket serverSocket = serverSocketChannel.socket();
//綁定端口號
serverSocket.bind(new InetSocketAddress(port));
//打開監聽器
selector = Selector.open();
//將通信信道注冊到監聽器
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//監聽器會一直監聽,如果客戶端有請求就會進入相應的事件處理
while (true) {
selector.select();//select方法會一直阻塞直到有相關事件發生或超時
Set<SelectionKey> selectionKeys = selector.selectedKeys();//監聽到的事件
for (SelectionKey key : selectionKeys) {
handle(key);
}
selectionKeys.clear();//清除處理過的事件
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 處理不同的事件
*
* @param selectionKey
* @throws IOException
*/
private void handle(SelectionKey selectionKey) throws IOException {
ServerSocketChannel serverSocketChannel = null;
SocketChannel socketChannel = null;
String requestMsg = "";
int count = 0;
if (selectionKey.isAcceptable()) {
//每有客戶端連接,即注冊通信信道為可讀
serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (selectionKey.isReadable()) {
socketChannel = (SocketChannel) selectionKey.channel();
rBuffer.clear();
count = socketChannel.read(rBuffer);
//讀取數據
if (count > 0){
rBuffer.flip(); //從緩存區頭部開始讀取數據操作
//緩存區讀取到的數據
requestMsg = String.valueOf(cs.decode(rBuffer).array()); }
//這里是處理從TCP接口上傳的數據業務層,一般可以在業務層根據switch case來對不同數據進行分類方法處理
xxxServices.dealMethods(requestMsg);
sBuffer = ByteBuffer.allocate(responseMsg.getBytes("UTF-8").length);
//一般responseMsg為從數據庫或其他數據源處獲取的數據字符串
//此處為指令下發
responseMsg=configurationMap.toString();
sBuffer.put(responseMsg.getBytes("UTF-8")); sBuffer.flip(); socketChannel.write(sBuffer); }
socketChannel.close(); } } } }