第一步
在web.xml中添加
<!-- socket用监听 start-->
<listener>
<description>Socket服务随web服务启动而启动</description>
<listener-class>com.job.SocketListener</listener-class>
</listener>
<!-- socket用监听 end-->
第二步
SocketListener.java
/**
* socket监控类——用于web启动时监控(具体配置在web.xml中)
*
* @author zk
*
*/
public class SocketListenerimplements ServletContextListener {
private ListenSocket socketThread;
/**
* 销毁当Servlet容器终止Web应用时调用该方法
*/
public void contextDestroyed(ServletContextEvent arg0) {
if (null != socketThread && !socketThread.isInterrupted()) {
// 关闭线程
socketThread.closeSocketServer();
// 中断线程
socketThread.interrupt();
}
}
/**
* 初始化当Servlet容器启动Web应用时调用该方法
*/
public void contextInitialized(ServletContextEvent arg0) {
if (null == socketThread) {
socketThread = new ListenSocket();
socketThread.start();
}
}
第三步
ListenSocket.java
/**
* socket服务端
*
* @author zk
*
*/
public class ListenSocket extends Thread {
private static final Logger log = LogManager.getLogger(ListenSocket.class);
// 端口号
private static final String port = SharedMethod.getInstance()
.getPropertyValue("call_back_port", "12865");
// 服务端socket
private ServerSocket serverScoket = null;
// 客戶端接收到信息
private BufferedReader in = null;
// 返回給客戶端的信息
private OutputStream out = null;
/**
* 无参构造方法
*/
public ListenSocket() {
try {
if (null == serverScoket) {
this.serverScoket = new ServerSocket(Integer.valueOf(port));
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 监听的线程
*/
public void run() {
while (!this.isInterrupted()) {
Socket client = null;
try {
client = serverScoket.accept();
log.debug("-----监听线程----start--------");
String ms = "Callbackaccepted " + client.getInetAddress()
+ ":" + client.getPort();
log.debug(ms);
// 接收请求的流
in = new BufferedReader(new InputStreamReader(client
.getInputStream()));
// 写入缓存
out = client.getOutputStream();
// 监听到的字符串长度
int len = 0;
// 监听到的字符串
String str = "";
char[] buf = new char[40960];
while ((len = in.read(buf)) > 0) {
// 读取
str = new String(buf, 0, len);
log.debug("-------获取的报文: " + str);
if (str != null && !"".equals(str)) {
.
.
.
.
.
.
} else {
log.info("---------客户端所传报文为空");
out.write("-1".getBytes());
break;
}
}
} catch (IOException ex) {
log.error("------服务端与客户端交互时异常", ex);
} finally {
try {
if (client != null) {
client.close();
}
} catch (IOException e) {
log.error("------clientclose error", e);
}
}
}
}
/**
* 关闭当前线程
*/
public void closeSocketServer() {
try {
if (null != serverScoket && !serverScoket.isClosed()) {
serverScoket.close();
}
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
第四步
客户端调用
/**
* @param args
*/
public static void main(String[] args) {
try {
String str = “hello”;
Socket socket = new Socket("127.0.0.1", 13856);//13856 12865
// 客户端发送给服务端信息
OutputStream socketOut = socket.getOutputStream();
socketOut.write(str.getBytes());
// 接收到的服务端返回信息
BufferedReader br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
String msg = null;
while ((msg = br.readLine()) != null)
System.out.println("------服务端返回码:"+msg);
} catch (UnknownHostException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}