启动自定义代码的方式
WebServer Initialized Event
@EventListener ( ApplicationReadyEvent . class ) @Component public class TcpServerListener implements ApplicationListener < WebServerInitializedEvent > { @Override public void onApplicationEvent ( WebServerInitializedEvent event) { updateServer. startServer ( 8082 ) ; } }
ServerSocket
基本代码
ServerSocket serverSocket = new ServerSocket ( 8080 ) ; while ( true ) { try { Socket clientSocket = serverSocket. accept ( ) ; clientSocket. close ( ) ; } catch ( IOException e) { e. printStackTrace ( ) ; } }
DataInputStream
@PostConstruct @Async public void startServer ( ) throws Exception { ServerSocket serverSocket = new ServerSocket ( 8082 ) ; log. info ( "服务端打开了 Server started on port {}" , 8082 ) ; while ( true ) { Socket socket = serverSocket. accept ( ) ; DataInputStream inputStream = new DataInputStream ( socket. getInputStream ( ) ) ; DataOutputStream outputStream = new DataOutputStream ( socket. getOutputStream ( ) ) ; log. info ( "服务端收到了连接:Accepted connection from client: {}" , socket. getInetAddress ( ) ) ; byte [ ] buffer = new byte [ 380 ] ; int bytesRead; while ( ( bytesRead = inputStream. read ( buffer) ) != - 1 ) { processBinaryData ( buffer, bytesRead, socket, outputStream) ; } inputStream. close ( ) ; outputStream. close ( ) ; socket. close ( ) ; } }
InputStreamReader 字符流
BufferedReader(new InputStreamReader(socket.getInputStream())) new PrintWriter(socket.getOutputStream(), true)
public class TcpServer { public static void main ( String [ ] args) { try { ServerSocket serverSocket = new ServerSocket ( 5555 ) ; System . out. println ( "服务器启动,等待客户端连接..." ) ; Socket socket = serverSocket. accept ( ) ; System . out. println ( "客户端已连接." ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( socket. getInputStream ( ) ) ) ; PrintWriter out = new PrintWriter ( socket. getOutputStream ( ) , true ) ; String message = in. readLine ( ) ; System . out. println ( "收到客户端消息:" + message) ; out. println ( "构建响应 JSON" ) ; socket. close ( ) ; serverSocket. close ( ) ; } catch ( IOException e) { e. printStackTrace ( ) ; } }
}
NIO Selector
ServerSocketChannel
@Configuration
public class TcpServerConfig { @EventListener ( ApplicationReadyEvent . class ) public void startServer ( ) { try { Selector selector = Selector . open ( ) ; ServerSocketChannel channel = ServerSocketChannel . open ( ) ; channel. configureBlocking ( false ) ; channel. bind ( new InetSocketAddress ( tcpIp, 8082 ) ) ; channel. register ( selector, SelectionKey . OP_ACCEPT ) ; log. info ( "===============Server started on port 8082===================" ) ; while ( true ) { int readyChannels = selector. select ( ) ; if ( readyChannels == 0 ) { continue ; } Set < SelectionKey > selectedKeys = selector. selectedKeys ( ) ; Iterator < SelectionKey > keyIterator = selectedKeys. iterator ( ) ; while ( keyIterator. hasNext ( ) ) { SelectionKey key = keyIterator. next ( ) ; if ( key. isAcceptable ( ) ) { SocketChannel clientSocketChannel = serverSocketChannel. accept ( ) ; clientSocketChannel. configureBlocking ( false ) ; clientSocketChannel. register ( selector, SelectionKey . OP_READ ) ; log. info ( "收到连接:Accepted connection from: {}" , clientSocketChannel. getRemoteAddress ( ) ) ; } else if ( key. isReadable ( ) ) { SocketChannel clientSocketChannel = ( SocketChannel ) key. channel ( ) ; ByteBuffer buffer = ByteBuffer . allocate ( 38 ) ; int bytesRead = - 1 ; try { bytesRead = clientSocketChannel. read ( buffer) ; } catch ( Exception e) { log. info ( "未读取到" ) ; e. printStackTrace ( ) ; } if ( bytesRead == - 1 ) { clientSocketChannel. close ( ) ; } else if ( bytesRead > 0 ) { buffer. flip ( ) ; byte [ ] data = new byte [ bytesRead] ; buffer. get ( data) ; processBinaryData ( data, bytesRead, clientSocketChannel) ; buffer. clear ( ) ; } } keyIterator. remove ( ) ; } } } catch ( Exception e) { e. printStackTrace ( ) ; }
}
private void sendUpdateMessage ( SocketChannel clientSocketChannel) { byte [ ] binaryData = hexStringToBytes ( "dfsfsdfdsaf" ) ; ByteBuffer buffer = ByteBuffer . allocate ( binaryData. length) ; buffer. put ( binaryData) ; buffer. flip ( ) ; while ( buffer. hasRemaining ( ) ) { try { clientSocketChannel. write ( buffer) ; log. info ( "发送了一次升级的消息" ) ; } catch ( IOException e) { log. info ( "发送升级失败" ) ; e. printStackTrace ( ) ; } } }