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();
}
}
}
Java Socket Client
最新推荐文章于 2023-12-29 01:37:55 发布