java web專案中使用Socket通訊多執行緒、長連線

osblog發表於2016-04-15

  很多時候在javaweb專案中我們需要用到Socket通訊來實現功能,在web中使用Socket我們需要建立一個監聽程式,在程式啟動時,啟動socket監聽。我們的應用場景是在java專案中,需要外接如一個硬體裝置,通過tcp通訊,獲取裝置傳上來的資料,並對資料做迴應。

  先看一下web的監聽程式碼:

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
 
public class AttendSocetListener  implements ServletContextListener{
    private SocketThread socketThread;
    public void contextDestroyed(ServletContextEvent arg0) {  
        if(null!=socketThread && !socketThread.isInterrupted())  
           {  
            socketThread.closeSocketServer();  
            socketThread.interrupt();  
           }  
    }  
  
    @Override  
    public void contextInitialized(ServletContextEvent arg0) {  
        // TODO Auto-generated method stub  
        if(null==socketThread)  
        {  
         //新建執行緒類  
         socketThread=new SocketThread(null);  
         //啟動執行緒  
         socketThread.start();  
        }  
    }   
}

  建立執行緒:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
 
 
public class SocketThread extends Thread
{
       private ServerSocket serverSocket = null;  
          
        public SocketThread(ServerSocket serverScoket){  
            try {  
                if(null == serverSocket){  
                    this.serverSocket = new ServerSocket(8877);  
                    System.out.println("socket start");  
                }  
            } catch (Exception e) {  
                System.out.println("SocketThread建立socket服務出錯");  
                e.printStackTrace();  
            }  
      
        }  
          
        public void run(){  
            while(true){  
                try {  
                    if(serverSocket==null){
                        break;
                    }else if(serverSocket.isClosed()){
                        break;
                    }
                    Socket socket = serverSocket.accept();  
                    if(null != socket && !socket.isClosed()){     
                        //處理接受的資料  
                        Thread t1 = new Thread(new SocketOperate(socket));  
                        t1.start();  
                    }else{
                        break;
                    }
                }catch (Exception e) {  
                    System.out.println("SocketThread建立socket服務出錯111111111111111111111111");  
                    e.printStackTrace();  
                    
                }  
            }  
        }  
          
        public void closeSocketServer(){  
           try {  
                if(null!=serverSocket && !serverSocket.isClosed())  
                {  
                 serverSocket.close();  
                }  
           } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
           }  
         }  
          
    }

  處理接受到的資料:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
 
public class SocketOperate implements Runnable {  
     private Socket socket;  
     //該執行緒所處理的Socket所對應的輸入流  
     BufferedReader br = null;  
     String str = null;  
     String content = null;  
     InputStreamReader reader=null;  
     public SocketOperate(Socket socket) throws IOException  
     {  
         this.socket = socket;  
         reader = new InputStreamReader(this.socket.getInputStream(),"utf-8");  
         br = new BufferedReader(reader);  
     }  
   
     @Override  
     public void run()  
     {  
         try  
         {  
             // 採用迴圈不斷從Socket中讀取客戶端傳送過來的資料  
            while (true)  
             {  
               content = readFromClient();  
               System.out.println(content);
            if (content == null)  
             {  
              break;  
             }  
             OutputStream os = socket.getOutputStream();  
             os.write(("RES, OK,<1年2班,小明>, 123241,#" + "\n").getBytes("utf-8"));  
             os.flush();
             }  
         }  
         catch (IOException e)  
         {  
          e.printStackTrace();  
         }  
     }  
     //定義讀取客戶端資料的方法  
     private String readFromClient()  
     {  
         try  
         {  
          str = br.readLine();  
          return str;  
           
         }  
         //如果捕捉到異常,表明該Socket對應的客戶端已經關閉  
         catch (IOException e)  
         {  
         try {
             br.close();
         reader.close();
            socket.close();
         } catch (IOException e1) {
             // TODO Auto-generated catch block
             e1.printStackTrace();
            } 
         }  
         return null;  
     }  
 }

  客戶端程式碼:

package
import java.io.*;
import java.net.*;
 
public class TalkClient {
 
    public static void main(String args[]) throws UnknownHostException, IOException {
         Socket socket=new Socket("192.168.3.104",8877);
         PrintWriter os=new PrintWriter(socket.getOutputStream());
         BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
         int i=1;
         while(socket.isConnected()){
         os.print("BEAT,12345678,160314,092832,1.00,123241,#"+"\n");
         os.flush();
         System.out.println("Client:"+i);
         System.out.println("Server:"+is.readLine());
         i++;
         } 
         //繼續迴圈
         os.close(); //關閉Socket輸出流
         is.close(); //關閉Socket輸入流
         socket.close(); //關閉Socket
            
            }
}

  本文地址:http://www.osblog.net/blog/676.html

相關文章