⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sample.java

📁 JAVA网络编程等几个小程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
这是一个TCP服务器端的实现代码,监听客户端的请求,在子线程中处理各个客户端发来的数据包,再将处理后的结果送回客户端。这里提供的代码很完整,包括一个mainclass,一个监听class和它的interface,一个包处理class,一个发送class,基本上可以直接使用。其中用到的一些工具类,例如Debug、GenProfile、Terminator等,它们代码也会出现在随后的系列文章中。


package org.kyle.net.svr.sample;

 

import java.io.*;

import java.util.*;

import java.net.*;

 

public class Sample

{

    // GenProfile是一个配置文件工具类,从配置文件中取得运行参数

   protected GenProfile m_env = null;

    protected IListener m_Listener = null;

 

    public Sample()

    {

    String cfgFile = System.getProperty("MainConfigFile","server.cfg");

        m_env = new GenProfile( cfgFile );

    }

 

    public boolean startService()

    {

        try

        {

            // IntegrationFactory是一个工厂类,创建一个Listener实例

            m_Listener=IntegrationFactory.createListener(m_env);

            m_Listener.setProfile(m_env);

            m_Listener.startListener();

            Debug.info("Server started.");

            return true;

        }

        catch( Exception e)

        {

            Debug.warning(e);

        }

        return false;

    }

 

    public boolean stopService()

    {

        try

        {

            m_ Listener.stopListener();

            Debug.info("Server service stopped.");

            return true;

        }

        catch( Exception e )

        {

            Debug.warning(e);

        }

        return false;

    }

 

    public static void main( String [] argv )

    {

        try

        {

          Sample main = new Sample();

          main.startService();

          // Terminator用来接收键盘操作,按下特定键后使程序退出。

          Terminator terminator = null;

          terminator = new Terminator(System.in, main);

          terminator.start();

          synchronized (main) {

            main.wait(); //将主进程悬挂,直到在Terminator里激活。

            main.stopService();

          }

          System.exit(0);

        }

        catch( Exception e )

        {

            Debug.warning(e);

        }

    }

}

 

 

package org.kyle.net.svr.sample;

 

import java.net.*;

 

public interface IListener

{

    public void setProfile( GenProfile env );

    public void listenOn(int port);

    public void setTimeout( int timeout );

    public void startListener();

    public void stopListener();

    public RawPkt accept();

    public void close();

}

 

 

 

package org.kyle.net.svr.sample;

 

import java.net.*;

import java.io.*;

import java.util.*;

import java.math.*;

 

public class SampleListenerImpl extends Thread implements IListener

{

    private boolean m_isRunning = false;

    private boolean m_innerCall = false;

    private int m_listenAt = -1;

    private int m_timeout = -1;

    private Socket m_skt = null;

    private ServerSocket m_svrSkt = null;

 

    public SampleListenerImpl ()

    {

        setName("SampleListener.");

    }

 

    public SampleListenerImpl ( GenProfile env )

        throws SocketException, SecurityException, IOException

    {

        setName("SampleListener.");

        if ( env == null )

            throw new SecurityException("No Environment provided!");

        m_env = env;

        invokeSocket();

    }

 

    public void setProfile( GenProfile env )

    {

        m_env = env;

    }

    public void run()

    {

        try

        {

            invokeSocket();

            Debug.info("Listening at " + m_svrSkt.getLocalPort() + "...");

            while( m_isRunning )

            {

                try

                {

                    m_innerCall = true;

                    accept();

                    m_innerCall = false;

                }

                catch( Exception e)

                {

                    Debug.info(e);

                }

            }

        }

        catch(Exception e)

        {

            Debug.info(e);

        }

    }

 

    public void startListener()

    {

        if ( !m_isRunning )

        {

            m_isRunning = true;

            start();

        }

    }

    public void stopListener()

    {

        if ( m_isRunning )

        {

            m_isRunning = false;

            interrupt();

            close();

        }

    }

 

    public RawPkt accept()

    {

        if ( m_isRunning )

        {

            if ( m_innerCall )

            { }

            else

            {

                Debug.finest("StandAlone Listener was started, external call of accept failed.");

                return null;

            }

        }

 

        try

        {

            m_skt = m_svrSkt.accept();

            m_skt.setSoTimeout( m_env.getTimeout() * 1000 );

            Debug.fine("ServerSocket accepted. ");

            new FreeListener( m_skt );

            return null;

        }

        catch( InterruptedIOException iioe)

        {

            Debug.info("Listener Timed Out: " + iioe.getMessage()  + "\n");

        }

        catch(IOException ioe)

        {

            Debug.info(ioe);

        }

        catch(Exception e)

        {

            Debug.info(e);

        }

        return null;

    }

 

    public void listenOn(int port)

    {

        if ( port < 0 || port > 65535 ) port = 0;

        m_listenAt = port;

    }

 

    public void close()

    {

        if ( m_skt != null )

        {

            if ( !m_isRunning )

            {

                try{

                    m_skt.close();

                    m_skt = null;

                }

                catch( IOException ioe)

                {

                    Debug.warning(ioe);

                }

            }

        }

    }

 

    public void setTimeout( int timeout )

    {

        if ( timeout < 0 ) timeout = 300;

        m_timeout = timeout;

    }

    /////////////Private methods section.///////////////////////////////

    private void invokeSocket()

        throws SocketException, SecurityException, IOException

    {

        if ( m_skt == null )

        {

            m_svrSkt = new ServerSocket( m_listenAt != -1 ? m_listenAt : m_env.getListenAt() );

            m_svrSkt.setSoTimeout( m_timeout != -1 ? m_timeout*1000: m_env.getTimeout()*1000 );

        }

    }

 

    class FreeListener extends Thread

    {

        Socket m_skt;

        public FreeListener( Socket skt )

        {

            m_skt = skt;

            start();

        }

 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -