java之接口开发-初级篇-socket通信

socket通信实现util包类实现

public class SocketThread extends Thread {
public void run() {
while (true) {
// log4j
Logger log = (Logger) LogManager.getLogger(SocketThread.class);
// 标识服务信息
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
ServerSocket ss;// socket服务监听对象
Socket socket;// 获取监听得到的结果
BufferedReader in;// 输入流
PrintWriter out;// 输出流
try {
// 设置监听的端口,并实例监听对象
ss = new ServerSocket(SocketConstants.SOCKET_PORT_NO_EC);
while (true) {

// 开始监听,若没有客户端请求则线程一直停留在这里等待请求,
// 一旦就有请求,就获取监听到的对象
socket = ss.accept();

InputStream sis = socket.getInputStream();// socket服务获取的输入流

// 等待读取状态
// 大于零为获取完毕
while (sis.available() <= 0)
System.out.println("inputStream is waitting...");

in = new BufferedReader(new InputStreamReader(sis));// 获取输入

String line = "";// 监听到的字符串

// 读数据
while (in.ready()) {
line += in.readLine();
}
// 记录下获取到的字符串流
log.warn("client request is :" + line);
out = new PrintWriter(socket.getOutputStream(), true);// 构建输出

// 输出
out.println("server response " + sdf.format(new Date()));
// 关闭当前请求对象
out.close();
in.close();
socket.close();
}
} catch (IOException e) {
String msg = "\n" + e.getMessage();
for (StackTraceElement ste : e.getStackTrace()) {
msg += "\n" + ste.getClassName() + "-" + ste.getFileName() + "-" + ste.getMethodName() + "-" + ste.getLineNumber();
}
log.fatal(msg);
} catch (Exception ex) {
String msg = "\n" + ex.getMessage();
for (StackTraceElement ste : ex.getStackTrace()) {
msg += "\n" + ste.getClassName() + "-" + ste.getFileName() + "-" + ste.getMethodName() + "-" + ste.getLineNumber();
}
log.fatal(msg);
}
}
}
}

posted @ 2019-03-12 19:28  ZXJ~佳  阅读(1761)  评论(0编辑  收藏  举报