Java Web项目中使用Socket通信多线程、长连接的方法
很多时候在javaweb项目中我们需要用到Socket通信来实现功能,在web中使用Socket我们需要建立一个监听程序,在程序启动时,启动socket监听。我们的应用场景是在java项目中,需要外接如一个硬件设备,通过tcp通信,获取设备传上来的数据,并对数据做回应。
先看一下web的监听代码:
importjavax.servlet.ServletContextEvent; importjavax.servlet.ServletContextListener; publicclassAttendSocetListenerimplementsServletContextListener{ privateSocketThreadsocketThread; publicvoidcontextDestroyed(ServletContextEventarg){ if(null!=socketThread&&!socketThread.isInterrupted()) { socketThread.closeSocketServer(); socketThread.interrupt(); } } @Override publicvoidcontextInitialized(ServletContextEventarg){ //TODOAuto-generatedmethodstub if(null==socketThread) { //新建线程类 socketThread=newSocketThread(null); //启动线程 socketThread.start(); } } }
创建线程:
importjava.io.IOException; importjava.net.ServerSocket; importjava.net.Socket; importjava.util.ArrayList; importjava.util.List; publicclassSocketThreadextendsThread { privateServerSocketserverSocket=null; publicSocketThread(ServerSocketserverScoket){ try{ if(null==serverSocket){ this.serverSocket=newServerSocket(); System.out.println("socketstart"); } }catch(Exceptione){ System.out.println("SocketThread创建socket服务出错"); e.printStackTrace(); } } publicvoidrun(){ while(true){ try{ if(serverSocket==null){ break; }elseif(serverSocket.isClosed()){ break; } Socketsocket=serverSocket.accept(); if(null!=socket&&!socket.isClosed()){ //处理接受的数据 Threadt=newThread(newSocketOperate(socket)); t.start(); }else{ break; } }catch(Exceptione){ System.out.println("SocketThread创建socket服务出错"); e.printStackTrace(); } } } publicvoidcloseSocketServer(){ try{ if(null!=serverSocket&&!serverSocket.isClosed()) { serverSocket.close(); } }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } }
处理接受到的数据:
importjava.io.BufferedReader; importjava.io.IOException; importjava.io.InputStreamReader; importjava.io.OutputStream; importjava.net.Socket; publicclassSocketOperateimplementsRunnable{ privateSocketsocket; //该线程所处理的Socket所对应的输入流 BufferedReaderbr=null; Stringstr=null; Stringcontent=null; InputStreamReaderreader=null; publicSocketOperate(Socketsocket)throwsIOException { this.socket=socket; reader=newInputStreamReader(this.socket.getInputStream(),"utf-"); br=newBufferedReader(reader); } @Override publicvoidrun() { try { //采用循环不断从Socket中读取客户端发送过来的数据 while(true) { content=readFromClient(); System.out.println(content); if(content==null) { break; } OutputStreamos=socket.getOutputStream(); os.write(("RES,OK,<年班,小明>,,#"+"\n").getBytes("utf-")); os.flush(); } } catch(IOExceptione) { e.printStackTrace(); } } //定义读取客户端数据的方法 privateStringreadFromClient() { try { str=br.readLine(); returnstr; } //如果捕捉到异常,表明该Socket对应的客户端已经关闭 catch(IOExceptione) { try{ br.close(); reader.close(); socket.close(); }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } returnnull; } }
客户端代码:
package importjava.io.*; importjava.net.*; publicclassTalkClient{ publicstaticvoidmain(Stringargs[])throwsUnknownHostException,IOException{ Socketsocket=newSocket("...",); PrintWriteros=newPrintWriter(socket.getOutputStream()); BufferedReaderis=newBufferedReader(newInputStreamReader(socket.getInputStream())); inti=; while(socket.isConnected()){ os.print("BEAT,,,,.,,#"+"\n"); os.flush(); System.out.println("Client:"+i); System.out.println("Server:"+is.readLine()); i++; } //继续循环 os.close();//关闭Socket输出流 is.close();//关闭Socket输入流 socket.close();//关闭Socket } }
以上所述是小编给大家介绍的JavaWeb项目中使用Socket通信多线程、长连接的方法,希望对大家有所帮助!