在前端想使用socket可以使用websocket,在这里提供另外一种方式来解决socket接收的数据在web前端显示的问题。

首先socket还是采用最常见的java语言中的socket类,这里需要将socket client置为Spring容器管理的类,这里将socket client置为service,并且为其配置一个list缓存接收到的数据,然后在controller中提供一个数据访问接口供ajax访问,并且添加一个runner,在Springboot启动的时候启动这个runner。

Talk is cheap,show me the code.

runner表示

@Component
@Order(value = 1)
public class SocketRunner implements ApplicationRunner {//或者也可以实现这个接口CommandLineRunner
    @Autowired
    SocketClientImpl client;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        client.doWork();
    }
}

client表示:

@Service
public class SocketClientImpl implements SocketClient {
    @Autowired
    private Position position;

    @Override
    public void doWork() {
        Socket client = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        ObjectOutputStream writer = null;
        ObjectInputStream reader = null;
        try {
            client = new Socket();
            InetAddress inetAddress = InetAddress.getLocalHost();
            InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 6666);
            client.connect(inetSocketAddress);
            inputStream = client.getInputStream();
            outputStream = client.getOutputStream();
            writer = new ObjectOutputStream(outputStream);
            if (client.isConnected()) {
                writer.writeInt(999);
                writer.flush();
            }
            reader = new ObjectInputStream(inputStream);
            int length = 1;
            while (length != -1) {
                length = reader.readInt();
                byte[] bytes = new byte[length];
                reader.read(bytes);
                System.out.println(new String(bytes));
                position.getList().add(new String(bytes));
                writer.writeInt(999);
                writer.flush();
                System.out.println(position.list.size() + ":" + position.list.hashCode());
                TimeUnit.SECONDS.sleep(3);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
                if(inputStream!=null){
                    inputStream.close();
                }
                if(outputStream!=null){
                    outputStream.close();
                }
                if(writer!=null){
                    writer.close();
                }
                if(reader!=null){
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    @Override
    public Position getResult() {
        return position;
    }
    }

controller层表示:

@GetMapping("socket")
@ResponseBody
public String socket(){
    String message=socketClientImpl.getResult().getList().get(0);
    socketClientImpl.getResult().getList().remove(0);
    return message;
}

前端Ajax表示:

function loadXMLHttp(){
    var xmlHttp;
    if (window.XMLHttpRequest){
        xmlHttp=new XMLHttpRequest();
    }else{
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlHttp.open("GET","/socket","true");
    xmlHttp.send();
    xmlHttp.onreadystatechange=function () {
        if (xmlHttp.readyState==4 && xmlHttp.status==200){
            doYourWork();
        }
    }
}
window.setInterval(loadXMLHttp,4000);
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐