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);
}
}
}
}