java socket多线程

摘要

在我的web程序启动的时候,程序后台自动开启一个线程,监听socket端口。在项目中使用了一个监听器去开启线程类:

1.在我的web程序启动的时候,程序后台自动开启一个线程,监听socket端口。在项目中使用了一个监听器去开启线程类:

package cn.ccb.yn.acms.socket;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
public class MyListener extends HttpServlet implements ServletContextListener  {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private ServerServiceImpl serverServiceImpl;
    public void contextInitialized(ServletContextEvent arg0) {
        if(null==serverServiceImpl){
            new ServerServiceImpl().start();
        }
    }
    public void contextDestroyed(ServletContextEvent arg0) {
        if(null!=serverServiceImpl && serverServiceImpl.isInterrupted()){
            serverServiceImpl.interrupt();
        }
                                                                                      
    }
}


下面是服务端线程类:

package cn.ccb.yn.acms.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.sql.Statement;
import org.springframework.stereotype.Service;
@Service
public class ServerServiceImpl extends Thread implements IServerService {
    ServerSocket serverSocket = null;
    Socket socket = null;
    BufferedReader bReader = null;
    PrintWriter pWriter = null;
    public ServerThread th = null;
                                                                    
    public void initPort(){
        try {
            if(null==serverSocket){
                serverSocket = new ServerSocket(22222);
            }
        } catch (IOException e) {
            if(null!=serverSocket){
                try {
                    serverSocket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }
    }
                                                                    
                                                                    
    public void run(){
        initPort();
        while(true){
            System.out.println("Listening Port 22222 Starting.....");
            try {
                socket = serverSocket.accept();
                th = new ServerThread(socket);
                th.start();
                                                                            
                sleep(1000);
                                                                                
            } catch (IOException e) {
                e.printStackTrace();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 使用一个内部类去处理服务器接收到的请求
     * @author yb
     *
     */
    class ServerThread extends Thread {
        Socket sk = null;  
        public ServerThread(Socket sk){
            this.sk = sk;
        }
        public void run(){
            try {
                pWriter = new PrintWriter(sk.getOutputStream());
                bReader = new BufferedReader(new InputStreamReader(sk.getInputStream()));  
                String line = bReader.readLine();
                if(null!=line && !"".equals(line)){
                    saveData(line);
                    System.out.println("从客户端来的信息:" + line); 
                    pWriter.println("你好,服务器已经收到您的信息!'" + line + "'\n");  
                }
                pWriter.flush();
                                                                                
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
                                                                    
    public static void main(String [] args)  
       {  
           //saveData();
           //new ServerServiceImpl().start();  
       }
                                                                    
    /**
     * 开启线程
     */
    public String startThread(){
        try {
            th.start();
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
         return "";
    }
    /**
     * 停止线程
     */
    @SuppressWarnings("deprecation")
    public String stopThread(){
        th.stop();
        return "";
    }
                                                                    
    /**
     * 处理数据
     * @param str
     * @return
     */
    public static String saveData(String str){
        try {
            Statement stmt = DBConnection.getOracleConn("jdbc:oracle:thin:@172.17.1.12:1521:odsbptdb", "acms", "acms").createStatement();
            String sql = "insert into TEST values (1,'"+str+"')";
            stmt.execute(sql);
            return "success";
        } catch (SQLException e) {
            e.printStackTrace();
            return "fail";
        }
    }
                                                                    
                                                                    
                                                                    
                                                                    
                                                                    
}

在web.xml中配置自定监听器

<listener>
    <listener-class>cn.ccb.yn.acms.socket.MyListener</listener-class>
</listener>



客户端测试类:

package cn.ccb.yn.acms.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client extends Thread {
    Socket sk = null;  
    BufferedReader reader = null;  
    PrintWriter wtr = null;  
    BufferedReader keyin = null;
    public Client()  
    {
        keyin = new BufferedReader(new InputStreamReader(System.in));  
        try 
        {  
            sk = new Socket("127.0.0.1", 22222);  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }  
    }
       
    public void run(){
        try {
            System.out.println("客户端开始请求.....");
            reader = new BufferedReader(new InputStreamReader(sk.getInputStream()));  
            wtr = new PrintWriter(sk.getOutputStream());  
            String get = keyin.readLine();
            while (true)  
            {  
                if (get != null & get.length() > 0)  
                {  
                    wtr.println(get);  
                    wtr.flush();  
                    //wtr.close();  
                    //System.out.println(get + "发送完毕");  
                }  
                if (reader != null)  
                {  
                    String line = reader.readLine();  
                    System.out.println("从服务器来的信息:" + line);  
                          
                }  
                                      
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
           
    }
    public static void main(String [] args)  
    {  
        new Client().start();  
    }
}


IT家园
IT家园

网友最新评论 (0)