package com.hxzkoa.tools;
|
|
import java.io.BufferedReader;
|
import java.io.BufferedWriter;
|
import java.io.IOException;
|
import java.io.InputStreamReader;
|
import java.io.OutputStreamWriter;
|
import java.net.ServerSocket;
|
import java.net.Socket;
|
import java.util.HashMap;
|
import java.util.Timer;
|
import java.util.TimerTask;
|
import java.util.concurrent.CountDownLatch;
|
|
import javax.annotation.PostConstruct;
|
|
import org.springframework.stereotype.Component;
|
|
import com.hxzkoa.util.StringUtil2;
|
|
@Component
|
public class SocketUtil {
|
|
static Socket socket = new Socket();
|
|
@PostConstruct
|
public void init() {
|
try {
|
final ServerSocket serverSocket = new ServerSocket(8888);
|
// System.out.println("Æô¶¯·þÎñÆ÷......");
|
Thread thread = new Thread(
|
new Runnable() {
|
public void run() {
|
while (true) {
|
try {
|
socket = serverSocket.accept();
|
// System.out.println(socket.getRemoteSocketAddress());
|
// System.out.println("¿Í»§¶Ë:"+socket.getInetAddress().getHostAddress()+"ÒÑÁ¬½Óµ½·þÎñÆ÷");
|
System.out.println(socket.getRemoteSocketAddress());
|
final BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
|
CountDownLatch countDownLatch = new CountDownLatch(1);
|
Timer timer = new Timer();
|
TimerTask task = new TimerTask() {
|
@Override
|
public void run() {
|
String msg;
|
try {
|
msg = br.readLine();
|
if (StringUtil2.isNotEmpty(msg)) {
|
System.out.println("------"+msg);
|
}
|
} catch (IOException e) {
|
// TODO ×Ô¶¯Éú³ÉµÄ catch ¿é
|
e.printStackTrace();
|
}
|
}
|
};
|
timer.schedule(task, 0, 5000);
|
new SocketUtil().sendmsg("ok");
|
} catch (Exception e) {
|
|
}
|
}
|
}
|
});
|
thread.start();
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
|
public void sendmsg(String msg) {
|
try {
|
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
|
bw.write(msg+"\n");
|
bw.flush();
|
// System.out.println("·¢ËÍÍê³É");
|
} catch (IOException e) {
|
throw new RuntimeException(e);
|
}
|
}
|
|
public void receivemsg() {
|
try {
|
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
|
String msg;
|
while (true) {
|
msg = br.readLine();
|
if (StringUtil2.isNotEmpty(msg)) {
|
// System.out.println("É豸·¢À´ÏûÏ¢:"+msg);
|
System.out.println("------"+msg);
|
}
|
}
|
} catch (IOException e) {
|
throw new RuntimeException(e);
|
}
|
}
|
|
}
|