Start the socket server startup time javaweb

Description: Starts socket server javaweb when the project started, and can accept data sent by the client, the client can be repeatedly disconnected

1. Create a new thread class SocketThread

package com.wlw.modules.startImplement.web;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * socket 线程类
 * @Author: zhouhe
 * @Date: 2019/4/16 14:58
 */
public class SocketThread extends Thread {
    private ServerSocket serverSocket = null;

    public SocketThread(ServerSocket serverScoket){
        try {
            if(null == serverSocket){
                this.serverSocket = new ServerSocket(8877);
                System.out.println("socket start");
            }
        } catch (Exception e) {
            System.out.println("SocketThread创建socket服务出错");
            e.printStackTrace();
        }

    }

    public void run(){
        while(!this.isInterrupted()){
            try {
                Socket socket = serverSocket.accept();

                if(null != socket && !socket.isClosed()){
                    //处理接受的数据
                    new SocketOperate(socket).start();
                }
//                socket.setSoTimeout(30000);   //设置超时

            }catch (Exception e) {

            }
        }
    }


    public void closeSocketServer(){
        try {
            if(null!=serverSocket && !serverSocket.isClosed())
            {
                serverSocket.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace (); 
        } 
    } 
}

 

2. Create SocketOperate, for receiving data from the client

package com.wlw.modules.startImplement.web;

import com.wlw.modules.lhjh.socket.tstandard.MessageParsing;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * 多线程处理socket接收的数据
 * @Author: zhouhe
 * @Date: 2019/4/16 14:59
 */
public class SocketOperate extends Thread {
    private Socket socket;

    public SocketOperate(Socket socket) {
        this.socket=socket;
    }

    @Override
    public  void RUN () {
         the try {
             // package input stream (stream receiving client) 
            BufferedInputStream BIS = new new BufferedInputStream (Socket.getInputStream ()); 
            DataInputStream DIS = new new DataInputStream (BIS);
             byte [] bytes = new new  byte [. 1 ]; // read one byte 

            String RET = "" ;
             the while (! dis.read (bytes) = -1 ) { 
                RET + = MessageParsing.bytesToHexString (bytes) + "" ;
                 IF(dis.available () == 0) { // request 

                    System.out.println ( "converted to a string:" + MessageParsing.hexStringToString (RET)); 
                    System.out.println ( "After turning the map data: "+ MessageParsing.stringToMap (MessageParsing.hexStringToString (RET))); 

                    RET =" " ; 
                } 
            } 
        } the catch (Exception E) { 
            e.printStackTrace (); 
        } the finally { 
            System.out.println ( " Client over IS " );
             IF ! (Socket = null ) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3. New InitJob, when the web project started inside the method will be executed, to start the socket, serial debugging tools can be used to test

Package com.wlw.modules.startImplement.web; 

Import com.wlw.common.config.Global; 

Import javax.servlet.ServletContextEvent;
 Import the javax.servlet.ServletContextListener; 

/ ** 
 * @author: zhouhe 
 * @date: 2019 / 4/16 11:00 
 * / 
// class name created according to the definition of needs, but we must implement the interface ServletContextListener 
public  class InitJob the implements ServletContextListener { 

    // socket Server thread 
    Private socketThread socketThread; 

    / ** 
     time * project would start initialization the method will be executed (execution start service) 
     * @param arg0
      * / 
    @Override 
    public void contextInitialized (ServletContextEvent arg0) {
         // TODO Auto-Generated Method, Stub
         // here you can put the code or the way you want to perform 
        IF ( null == socketThread && "yes" .equals (Global.getConfig ( "socket" ))) {
 //             MessageParsing.calculation ();
             // new thread class 
            socketThread = new new socketThread ( null );
             // start threads 
            socketThread.start (); 
        } 
    } 

    / ** 
     * is a method performed in the contextDestroyed demise when (Close service when executed) 
     * @param arg0
      * /
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        if(null!=socketThread && !socketThread.isInterrupted()){
            socketThread.closeSocketServer();
            socketThread.interrupt();
        }
    }

}

4. It should be a packet-based analysis tool

package com.wlw.modules.lhjh.socket.tstandard;

import java.util.HashMap;
import java.util.Map;

/**
 * HJ/T212 报文解析
 * @Author: zhouhe
 * @Date: 2019/4/12 10:11
 */
public class MessageParsing {
    /**
     * 字符串转换为 map
     * @param arr
     * @return
     */
    public static Map stringToMap(String arr){
        arr=arr.replaceAll(",",";");
        Map map = new HashMap();
        if (null !=ARR) { 
            String [] param = arr.split ( ";" );
             for ( int I = 0; I <param.length; I ++ ) {
                 // index to herein> -1 format is the map 
                int index = param [I] .indexOf ( '=' );
                 IF (index> -1 ) 
                    map.put (param [I] .substring ( 0, index), param [I] .substring ((index +. 1 ))); 
            } 
        } 
        return Map; 
    } 

    / ** 
     * byte [] array is converted to a hexadecimal string 
     * 
     * @param byte array of bytes to be converted 
     * @returnThe conversion result
      * / 
    public  static String bytesToHexString ( byte [] bytes) { 
        the StringBuilder SB = new new the StringBuilder ();
         for ( int I = 0; I <bytes.length; I ++ ) { 
            String hex = Integer.toHexString (0xFF & bytes [I]);
             IF (hex.length () ==. 1 ) { 
                sb.append ( '0' ); 
            } 
            sb.append (hex); 
        } 
        return sb.toString (); 
    } 

    / ** 
     * 16 into string string type manufactured converted into 
     * this method Chinese will be garbled, letters and numbers will not be garbled 
     * 
     * @author zhouhe 
     * @param S 
     * @return 
     * / 
    public  static String hexStringToString (String S) {
         IF (S == null || s.equals ( "" )) {
             return  null ; 
        } 
        S = s.replace does ( "", "" );
         byte [] = baKeyword new new  byte [s.length () / 2 ];
         for ( int I = 0; I <baKeyword.length; ++ I ) {
             the try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "UTF-8");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }
}

That's it, start the web project, the client can accept data over the

Guess you like

Origin www.cnblogs.com/zhouheblog/p/11245833.html