Java Socket Client

import com.cmsen.common.socket.SocketThread;
import com.cmsen.common.util.ByteUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Author OWTS 
 * @Date 2020/8/25
 * @Description
 */
@Component
@Slf4j
public class SocketService {

    private static Socket socket = null;

    private static OutputStream dos = null;

    private static InputStream is = null;

    private boolean flag = false;

    private BlockingQueue<byte[]> queueMsg = new LinkedBlockingQueue<>();

    public SocketService() {
        SocketThread.create(this::initSocket).start();
    }

    private void initSocket() {
        try {
            log.warn("Socket Init:  " + "localhost : " + 2000);
            socket = new Socket("localhost", 2000);
            socket.setKeepAlive(true);
            dos = socket.getOutputStream();
            is = socket.getInputStream();
            if (socket.isConnected()) {
                log.warn("Socket Init Success:  " + "localhost : " + 2000);
            }
            SocketThread.create(this::message).start();
            SocketThread.create(this::reMessage).start();
        } catch (IOException e) {
            System.err.println(e.getMessage());
            log.warn("Socket Init Error:  " + "localhost : " + 2000);
            SocketThread.sleep(10000);
            initSocket();
        }
    }

    private void releaseSocket() {
        try {
            if (dos != null) {
                dos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (is != null) {
                is.close();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        dos = null;
        is = null;
        socket = null;
    }

    public void sendMessage(int header, int type, int taskNo, int status, int tail) {
        byte[] message = ByteUtil.merger(
            ByteUtil.toBytes2(header),
            ByteUtil.toBytes2(type),
            ByteUtil.toBytes2(taskNo),
            ByteUtil.toBytes2(status),
            ByteUtil.toBytes2(tail)
        );
        queueMsg.offer(message);
    }

    public void message() {
        while (true) {
            if (!queueMsg.isEmpty()) {
                flag = false;
                int count = 0;
                byte[] bytes = queueMsg.poll();
                while (!flag && count < 5) {
                    log.warn("Send Message data: " + ByteUtil.toHex(bytes));
                    try {
                        dos.write(bytes);
                        dos.flush();
                        log.warn("Send Message success: " + ByteUtil.toHex(bytes));
                        count++;
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                        releaseSocket();
                        initSocket();
                    }
                }
                if (count > 4) {
                    System.out.println("System Error...");
                }
            }
        }
    }

    public void onMessage() {
        try {
            byte[] bytes = new byte[8];
            while ((is.read(bytes)) != -1) {
                String s = ByteUtil.toHex(bytes);
                flag = true;
                log.warn("Receiving Message >>>>" + ">>>>>>" + s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void reMessage() {
        while (true) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            onMessage();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值