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

📄 sample.java

📁 JAVA网络编程等几个小程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:

        public void run()

        {

            try

            {

                DataInputStream is = new DataInputStream(m_skt.getInputStream());

                while( true )

                {//这里可能收到两种包,一种是http包,一种是自定义的包,在自定义的包中,约定了第3第4个字节是这个包的长度。

                    byte[] pktHd = new byte[4];

                    byte[] rawData = null;

                    is.readFully(pktHd);

                    boolean bUseHttp = false;

                    String method = new String(pktHd);

                    if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("GET ") || method.equalsIgnoreCase("PUT ")

                    || method.equalsIgnoreCase("DELE") || method.equalsIgnoreCase("HEAD") || method.equalsIgnoreCase("LINK")

                    || method.equalsIgnoreCase("UNLI"))

                    {

                        String url = is.readLine();

                        Debug.info(("\nHttp Packet received from [" +

                              m_skt.getInetAddress().getHostAddress() + ":" +

                              m_skt.getPort() + " --" + method + url) );

 

                        int len = 0;

                        if (method.equalsIgnoreCase("POST"))

                        {

                          do {

                            String s = is.readLine();

                            if (s == null)

                              throw new IOException("Not a HTTP request");

                            if (s.equals(""))

                              break;

                            int index = s.indexOf(':');

                            if (index == -1)

                              continue;

                            String name = s.substring(0, index);

                            String value = s.substring(index + 1);

                            if ("Content-Length".equalsIgnoreCase(name.trim()))

                               len = Integer.parseInt(value.trim());

                            } while(true);

                            Debug.finer("Content-Length=" + len);

                        }

                        if (len == 0) {m_skt.close();break;} //Must a hacker! close socket.

                        rawData = new byte[len];

                        is.readFully(rawData);

                        while(is.available() != 0) is.skip(is.available());

                        bUseHttp = true;

                    }

                    else

                    {

                        BigInteger bgInt = new BigInteger( new byte[] { pktHd[2], pktHd[3] } );

                        int rstLen = bgInt.intValue() - 4;

                        if ( rstLen <= 0 )

                            if ( m_env.statelessService() ) break;

                            else continue;

                        Debug.info("\nPacket received from [" +

                              m_skt.getInetAddress().getHostAddress() + ":" +

                              m_skt.getPort() + "]; total len:" + bgInt.intValue() +

                              ",rest len:" + rstLen);

                        rawData = new byte[rstLen + 4];

                        System.arraycopy(pktHd, 0, rawData, 0, 4);

                        is.readFully(rawData, 4, rstLen);

                        bUseHttp = false;

                    }

                    //RawPkt封装了收到的包

                    RawPkt nPkt = new RawPkt(rawData, m_skt.getInetAddress(), m_skt.getPort() );

                    // SamplePacketHandler类用来处理收到的包,SampleSender类用来向客户端发送数据。

                    SamplePacketHandler handler = new SamplePacketHandler ( nPkt, new SampleSender( m_skt, m_env, bUseHttp) );

                    handler.start();

                    handler = null;

                    if ( m_env.statelessService() ) break;

                }

            }

            catch( Exception e )

            {

                Debug.info(e);

            }

        }

    }

}

 

 

package org.kyle.net.svr.sample;

 

import java.util.*;

import java.math.*;

 

public class SamplePacketHandler extends Thread

{

    protected SampleSender m_sender = null;

    protected GenProfile m_env = null;

    private RawPkt m_rawPkt = null;

 

    public SamplePacketHandler(RawPkt rawPkt, GenProfile env, SampleSender sender)

    {

        m_rawPkt = rawPkt;

        m_env = env;

        m_sender = sender;

    }

 

    public void run()

    {

        if ( !m_sender.hasDestInfo() )

        {

            m_sender.setDestinationAddress( m_rawPkt.getSrcAddress() );

            m_sender.setDestinationPort( m_rawPkt.getSrcPort() );

        }

        

        //在这里对收到的数据包进行处理,结果封装在resPkt中。

        m_sender.send( resPkt );

   }

 

 

package org.kyle.net.svr.sample;

 

import java.net.*;

import java.util.*;

import java.io.*;

 

public class SampleSender

{

    private GenProfile m_profile = null;

    private InetAddress m_srcAddress = null;

    private int m_srcPort = -1;

    private InetAddress m_dstAddress = null;

    private int m_dstPort = -1;

    private boolean m_bUseHttp;

    private Socket m_skt = null;

 

    public SampleSender( GenProfile profile )

        throws SocketException

    {

        this( null, profile );

    }

 

    public SampleSender( Socket skt, GenProfile profile )

        throws SocketException

    {

        this( skt, profile, false );

    }

 

    public SampleSender( Socket skt, GenProfile profile, boolean bUseHttp)

        throws SocketException

    {

        if ( profile == null)

            throw new SocketException("null profile.");

        m_skt = skt;

        m_profile = profile;

        m_bUseHttp = bUseHttp;

    }

 

    public void setSourceAddress(InetAddress srcAddr)

    {

        m_srcAddress = srcAddr;

    }

 

    public void setDestinationAddress(InetAddress dstAddr)

    {

        m_dstAddress = dstAddr;

    }

 

    public void setSourcePort(int srcPort)

    {

        m_srcPort = srcPort;

    }

 

    public boolean hasDestInfo()

    {

        return !( m_dstAddress == null || m_dstPort == -1 || m_dstPort <= 0 || m_dstPort >= 65535);

    }

 

    public void setDestinationPort(int dstPort)

    {

        m_dstPort = dstPort;

    }

 

    public boolean send(InfoPacket msg)

    {

        //将InfoPacket编码为一个字节数组

Encoder encoder = new Encoder();

        encoder.setProfile( m_profile );

        byte[] baPkt = encoder.encode( msg );

 

        if ( baPkt == null || !hasDestInfo())

            return false;

        try

        {

            OutputStream os =  getSocket().getOutputStream();

            if (m_bUseHttp)

            {

                os.write(("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Length: " + baPkt.length + "\r\n\r\n").getBytes());

            }

 

            os.write( baPkt );

            os.flush();

            if ( m_profile.statelessService() )

            {

                os.close();

                m_skt.close();

            }

 

            return true;

        }

        catch( IOException ioe )

        {

            Debug.info(ioe);

        }

        catch( Exception e )

        {

            Debug.info(e);

        }

 

        return false;

    }

 

    public InetAddress getSrcAddress()

    {

        return m_srcAddress;

    }

 

    public void setSrcAddress(InetAddress aSrcAddress)

    {

        m_srcAddress = aSrcAddress;

    }

 

    public int getSrcPort()

    {

        return m_srcPort;

     }

 

    public void setSrcPort(int aSrcPort)

    {

        m_srcPort = aSrcPort;

     }

 

    private Socket getSocket()

    {

        if ( m_skt != null ) return m_skt;

        if ( !hasDestInfo() ) return null;

        try

        {

            if ( m_srcAddress != null && m_srcPort != -1 )

                return new Socket( m_dstAddress, m_dstPort, m_srcAddress, m_srcPort );

 

            return new Socket( m_dstAddress, m_dstPort );

        }

        catch(SocketException se)

        {

            Debug.info(se);

        }

        catch( Exception e )

        {

            Debug.info(e);

        }

        return null;

    }

 

}

⌨️ 快捷键说明

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