socket客户端监听接收数据

添加依赖:

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.3</version>
</dependency>

socket客户端:

import org.apache.commons.net.telnet.TelnetClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

public class SocketClient {

    private static Logger logger = LoggerFactory.getLogger(SocketClient.class);

    /**
     * 服务端ip
     */
    private static final String HOST_IP = "127.0.0.1";
    /**
     * 服务端端口
     */
    private static final Integer HOST_PORT = 8888;
    /**
     * 服务端登入命令
     */
    private static final String LOGIN_CMD = "";

    /**
     * 报文的分隔符
     */
    private static final String END_TAG = "</end>";

    /**
     * 字符编码
     */
    private static final String CHAR_CODE = "UTF-8";

    /**
     * 多少毫秒后没有接受到消息关闭客户端
     */
    private static final long NO_MSG_CLOSED = 10000;

    /**
     * 是否登录
     **/
    private boolean loginFlag = false;

    private TelnetClient client = null;

    public void run() {
        // 字符输入流
        InputStreamReader rs = null;
        StringBuffer sb = new StringBuffer();
        char[] buf = null;
        int endTagLength = END_TAG.length();

        long sendMillis = System.currentTimeMillis();
        long nowMillis = 0L;
        while (true) {
            if (!loginFlag) {
                logger.info("Socket未连接服务端,连接服务端");
                loginServer();
                if (!loginFlag) {
                    closeClient();
                    logger.info("连接失败,沉睡10s 再次连接服务端");
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        logger.info("异常", e);
                    }
                    continue;
                }
                logger.info("登入成功 开始接收消息.......");
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException ex) {
                logger.warn("sleep 异常", ex);
            }

            int len = 0;
            String msg = "";
            try {
                rs = new InputStreamReader(client.getInputStream(), CHAR_CODE);
                buf = new char[1024 * 8];
                while (rs.ready()) {
                    len = rs.read(buf, 0, buf.length);
                    sendMillis = System.currentTimeMillis();
                    msg = new String(buf, 0, len);
                    sb.append(msg);
                    int index = -1;
                    while ((index = sb.indexOf(END_TAG)) >= 0) {
                        msg = sb.substring(0, index + endTagLength);
                        logger.info(String.format("找到结尾标识的消息:[%s]", msg));
                        //TODO 可以将得到的数据发送到内存队列,由其他线程处理
                        //处理完后从StringBuffer中删除
                        sb.delete(0, index + endTagLength);
                    }
                }
                nowMillis = System.currentTimeMillis();
                if (nowMillis - sendMillis > NO_MSG_CLOSED) {
                    sendMillis = nowMillis;
                    logger.info("{}ms没有接受到告警 重启socket", NO_MSG_CLOSED);
                    closeClient();
                }
            } catch (Exception ex) {
                logger.error("receive message failed", "接告警类异常:", ex);
                closeClient();
            }
        }

    }

    private void loginServer() {
        try {
            client = new TelnetClient();
            logger.info(String.format("创建客户端, 开始连接([%s] [%s])", HOST_IP, HOST_PORT));
            client.connect(HOST_IP, HOST_PORT);
            TimeUnit.SECONDS.sleep(2);
            logger.info("输入登入命令");
            //sendCommand(LOGIN_CMD); // 登入命令
            loginFlag = true;
        } catch (Exception ex) {
            logger.error("connect failed", "连接服务端失败", ex);
            loginFlag = false;
        }
    }

    private void sendCommand(String command) throws IOException {
        logger.info(String.format("执行telnet命令: [%s]", command));
        OutputStream outStream = client.getOutputStream();
        for (int i = 0; i < command.length(); i++) {
            outStream.write(command.charAt(i));
        }
        outStream.flush();
    }

    private void closeClient() {
        try {
            logger.info("关闭客户端");
            if (client != null) {
                client.disconnect();
            }
            loginFlag = false;
            client = null;
        } catch (Exception e) {
            logger.error("close client failed", "关闭连接失败", e);
        }
    }

    public static void main(String[] args) {
        new SocketClient().run();
    }
}

socket服务端:

import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

public class SocketServer {

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("启动 8888 socket服务");
        Socket socket = serverSocket.accept();
        while (true) {
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("hello</end>".getBytes());
            TimeUnit.SECONDS.sleep(1);
        }
    }
}

 

posted @ 2022-06-11 14:47  残城碎梦  阅读(1252)  评论(0编辑  收藏  举报