tomcat 7 源码分析-9 tomcat对ServerSocket的封装和使用

本文深入探讨了Tomcat中ServerSocket的封装及使用方式,并通过示例代码展示了如何监听8080端口接收HTTP请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tomcat 7 源码分析-9 tomcat对ServerSocket的封装和使用

 

tomcat中ServerSocket线程监听是否有socket连接,如果有就转而处理。这个过程类似于你向tomcat发送一个URL请求,实质这个请求转换成http协议,通过socket发出来。

先看ServerSocket的封装主要为

Java代码   收藏代码
  1. public   abstract   class  ServerSocketFactory  implements  Cloneable  
public abstract class ServerSocketFactory implements Cloneable
 
Java代码   收藏代码
  1. class  DefaultServerSocketFactory  extends  ServerSocketFactory {  
  2.   
  3.     DefaultServerSocketFactory () {  
  4.         /* NOTHING */   
  5.     }  
  6.   
  7.     @Override   
  8.     public  ServerSocket createSocket ( int  port)  
  9.     throws  IOException {  
  10.         return    new  ServerSocket (port);  
  11.     }  
  12.   
  13.     @Override   
  14.     public  ServerSocket createSocket ( int  port,  int  backlog)  
  15.     throws  IOException {  
  16.         return   new  ServerSocket (port, backlog);  
  17.     }  
  18.   
  19.     @Override   
  20.     public  ServerSocket createSocket ( int  port,  int  backlog,  
  21.         InetAddress ifAddress)  
  22.     throws  IOException {  
  23.         return   new  ServerSocket (port, backlog, ifAddress);  
  24.     }  
  25.    
  26.     @Override   
  27.     public  Socket acceptSocket(ServerSocket socket)  
  28.     throws  IOException {  
  29.     return  socket.accept();  
  30.     }  
  31.    
  32.     @Override   
  33.     public   void  handshake(Socket sock)  
  34.     throws  IOException {  
  35.         // NOOP   
  36.     }  
  37.           
  38.           
  39.  }  
class DefaultServerSocketFactory extends ServerSocketFactory {

    DefaultServerSocketFactory () {
        /* NOTHING */
    }

    @Override
    public ServerSocket createSocket (int port)
    throws IOException {
        return  new ServerSocket (port);
    }

    @Override
    public ServerSocket createSocket (int port, int backlog)
    throws IOException {
        return new ServerSocket (port, backlog);
    }

    @Override
    public ServerSocket createSocket (int port, int backlog,
        InetAddress ifAddress)
    throws IOException {
        return new ServerSocket (port, backlog, ifAddress);
    }
 
    @Override
    public Socket acceptSocket(ServerSocket socket)
 	throws IOException {
 	return socket.accept();
    }
 
    @Override
    public void handshake(Socket sock)
 	throws IOException {
        // NOOP
    }
 	    
        
 }

 做了个小例子,模拟8080端口,可以通过浏览器想serversocket发消息。

Java代码   收藏代码
  1. package  com.test.socket;  
  2. import  java.io.*;  
  3. import  java.io.IOException;  
  4. import  java.net.ServerSocket;  
  5. import  java.net.Socket;  
  6. import  org.apache.tomcat.util.net.*;  
  7. public   class  testendpoint {  
  8.   
  9.     protected   volatile   boolean  running =  false ;  
  10.     /**  
  11.      * Server socket acceptor thread.  
  12.      */   
  13.     protected  ServerSocket serverSocket =  null ;  
  14.     protected  ServerSocketFactory serverSocketFactory =  null ;  
  15.     public   void  start()  throws  Exception {  
  16.         running = true ;  
  17.         //获得serverSocketFactory   
  18.         serverSocketFactory = ServerSocketFactory.getDefault();  
  19.         //获得serverSocket,监听8080端口   
  20.         serverSocket = serverSocketFactory.createSocket(8080 );  
  21.         //建立监听线程   
  22.         Thread acceptorThread = new  Thread( new  Acceptor(), "-Acceptor-" );  
  23.         acceptorThread.start();  
  24.     }  
  25.       
  26.     //处理socket   
  27.     protected   boolean  processSocket(Socket socket)  throws  IOException {  
  28.         BufferedReader in = new  BufferedReader( new  InputStreamReader(  
  29.                         socket.getInputStream()));  
  30.         String inputLine;  
  31.         while  ((inputLine = in.readLine()) !=  null ) {     
  32.             System.out.println(inputLine);  
  33.         }  
  34.   
  35.         return   true ;  
  36.     }  
  37.     //监听类,不断循环   
  38.     protected   class  Acceptor  implements  Runnable {  
  39.   
  40.         /**  
  41.          * The background thread that listens for incoming TCP/IP connections and  
  42.          * hands them off to an appropriate processor.  
  43.          */   
  44.         public   void  run() {  
  45.   
  46.             // Loop until we receive a shutdown command   
  47.             while  (running) {  
  48.   
  49.                 // Loop if endpoint is paused   
  50.                 // Accept the next incoming connection from the server socket   
  51.                 try  {  
  52.                     Socket socket = serverSocketFactory.acceptSocket(serverSocket);  
  53.                     serverSocketFactory.initSocket(socket);  
  54.                     // Hand this socket off to an appropriate processor   
  55.                     if  (!processSocket(socket)) {  
  56.                         // Close socket right away   
  57.                         try  {  
  58.                             socket.close();  
  59.                         } catch  (IOException e) {  
  60.                             // Ignore   
  61.                         }  
  62.                     }  
  63.                 }catch  ( IOException x ) {  
  64.                       
  65.                 } catch  (Throwable t) {  
  66.                       
  67.                 }  
  68.   
  69.                 // The processor will recycle itself when it finishes   
  70.   
  71.             }  
  72.   
  73.         }  
  74.   
  75.     }  
  76. }  
package com.test.socket;
import java.io.*;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.tomcat.util.net.*;
public class testendpoint {

	protected volatile boolean running = false;
	/**
     * Server socket acceptor thread.
     */
	protected ServerSocket serverSocket = null;
	protected ServerSocketFactory serverSocketFactory = null;
	public void start() throws Exception {
		running = true;
		//获得serverSocketFactory
		serverSocketFactory = ServerSocketFactory.getDefault();
		//获得serverSocket,监听8080端口
		serverSocket = serverSocketFactory.createSocket(8080);
		//建立监听线程
		Thread acceptorThread = new Thread(new Acceptor(),"-Acceptor-");
		acceptorThread.start();
	}
	
	//处理socket
	protected boolean processSocket(Socket socket) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(
                		socket.getInputStream()));
		String inputLine;
		while ((inputLine = in.readLine()) != null) {	
		    System.out.println(inputLine);
		}

		return true;
	}
	//监听类,不断循环
    protected class Acceptor implements Runnable {

        /**
         * The background thread that listens for incoming TCP/IP connections and
         * hands them off to an appropriate processor.
         */
        public void run() {

            // Loop until we receive a shutdown command
            while (running) {

                // Loop if endpoint is paused
                // Accept the next incoming connection from the server socket
                try {
                    Socket socket = serverSocketFactory.acceptSocket(serverSocket);
                    serverSocketFactory.initSocket(socket);
                    // Hand this socket off to an appropriate processor
                    if (!processSocket(socket)) {
                        // Close socket right away
                        try {
                            socket.close();
                        } catch (IOException e) {
                            // Ignore
                        }
                    }
                }catch ( IOException x ) {
                    
                } catch (Throwable t) {
                	
                }

                // The processor will recycle itself when it finishes

            }

        }

    }
}
 
Java代码   收藏代码
  1. package  com.test.socket;  
  2. import  org.apache.tomcat.util.net.*;  
  3. public   class  Servertest {  
  4.   
  5.     /**  
  6.      * @param args  
  7.      */   
  8.     public   static   void  main(String[] args) {  
  9.         // TODO Auto-generated method stub   
  10.           
  11.         testendpoint ts = new  testendpoint();  
  12.         try  {  
  13.             System.out.println("Server start" );  
  14.             ts.start();  
  15.         } catch  (Exception e) {  
  16.             // TODO Auto-generated catch block   
  17.             e.printStackTrace();  
  18.         }  
  19.           
  20.     }  
  21.   
  22. }  
package com.test.socket;
import org.apache.tomcat.util.net.*;
public class Servertest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		testendpoint ts = new testendpoint();
		try {
			System.out.println("Server start");
			ts.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
 

测试,在你的浏览器上输入:http://localhost:8080/

可以看见发过来的request的整个消息

Server start
GET / HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.7) Gecko/20100713 Firefox/3.6.7
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive

当然也可以写个客户端,向服务器端发数据。

Java代码   收藏代码
  1. package  com.test.socket;  
  2. import  java.net.Socket;  
  3. import  java.net.UnknownHostException;  
  4. import  java.io.*;  
  5. public   class  ClientTest {  
  6.   
  7.     /**  
  8.      * @param args  
  9.      */   
  10.     public   static   void  main(String[] args) {  
  11.         // TODO Auto-generated method stub   
  12.        //String host="127.0.0.1";   
  13.        String host = "localhost" ;  
  14.         Socket socket = null ;  
  15.         try  {  
  16.             socket = new  Socket(host, 8080 );  
  17.         } catch  (UnknownHostException e1) {  
  18.             // TODO Auto-generated catch block   
  19.             e1.printStackTrace();  
  20.         } catch  (IOException e1) {  
  21.             // TODO Auto-generated catch block   
  22.             e1.printStackTrace();  
  23.         }  
  24.                   
  25.         try  {  
  26.             PrintWriter out = new  PrintWriter(socket.getOutputStream(),  true );  
  27.             out.println("Send to host1" );  
  28.             out.println("Send to host2" );  
  29.         } catch  (IOException e) {  
  30.             // TODO Auto-generated catch block   
  31.             e.printStackTrace();  
  32.         }  
  33.           
  34.     }  
  35.   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值