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

📄 tcphttpport.java

📁 用java实现的
💻 JAVA
字号:
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.qq;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import edu.tsinghua.lumaqq.qq.events.QQEvent;
import edu.tsinghua.lumaqq.qq.packets.InPacket;
import edu.tsinghua.lumaqq.qq.packets.OutPacket;
import edu.tsinghua.lumaqq.qq.packets.Packet;
import edu.tsinghua.lumaqq.qq.packets.PacketHelper;

/**
 * <pre>
 * TCP登录,使用HTTP代理的连接类
 * </pre>
 * 
 * @author 马若劼
 */
public class TCPHttpPort extends AbstractPort implements IProxyHandler, INIOHandler {
    /** Log类 */
	private static final Log log = LogFactory.getLog(TCPHttpPort.class);
	/** 用于连接proxy也用于发送实际数据的channel */
	private SocketChannel channel;

	/** HTTP代理类 */
	private HttpProxy proxy;
    /** 代理是否已经准备好 */
	private boolean ready;
    
	/**
	 * 构造函数
	 * @param proxyAddress
	 * @param serverAddress
	 * @throws IOException
	 */
	public TCPHttpPort(InetSocketAddress proxyAddress, InetSocketAddress serverAddress) throws IOException {
	    this(proxyAddress, serverAddress, null, null);
	}
	
    /**
     * 构造函数
     * @param proxyAddress
     * @param serverAddress
     * @param u
     * @param p
     * @throws IOException
     */
    public TCPHttpPort(InetSocketAddress proxyAddress, InetSocketAddress serverAddress, String u, String p) throws IOException {
        ready = false;
        // 创建代理类
        proxy = new HttpProxy(porter, this, u, p);
        proxy.setProxyAddress(proxyAddress);
        proxy.setServerAddress(serverAddress);
    }

    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.AbstractPort#dispose()
     */
    public void dispose() throws IOException {
        super.dispose();
        proxy.dispose();
    }
    
    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.AbstractPort#start()
     */
    public void start() {
        super.start();
        proxy.start();
    }
    
    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.IProxyHandler#proxyReady(java.net.InetSocketAddress)
     */
    public void proxyReady(InetSocketAddress bindAddress) throws IOException {
        ready = true;
        channel = proxy.channel();
		porter.setNIOHandler(this);
    }

    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.IProxyHandler#proxyAuthFail()
     */
    public void proxyAuthFail() {
        proxyError(new Exception("Proxy Auth Fail"));
    }
    
    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.IProxyHandler#proxyError(java.lang.Exception)
     */
    public void proxyError(Exception e) {
        QQEvent event = new QQEvent(e);
        event.type = QQEvent.QQ_PROXY_ERROR;
        fireQQEvent(event);
    }

    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.IPort#channel()
     */
    public SelectableChannel channel() {
        return channel;
    }

    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.IPort#receive()
     */
    public void receive() throws IOException, PacketParseException {
		//接收数据
		for (int r = channel.read(receiveBuf); r > 0; r = channel.read(receiveBuf))
		    ;
		// 得到当前位置和limit,如果目前的数组小于两字节,也就是连个包长都没有,返回
		int pos = receiveBuf.position();
		if(pos < 2) return;
		//log.debug("目前总共有" + pos + "字节数据");
		// 置读取pos为0,limit为目前数据长度
		receiveBuf.flip();
		int readPos = 0;
	    // 得到包长
	    int len = receiveBuf.getChar(readPos);
		// 检查是否得到了至少一个完整的包
	    while(readPos + len <= pos) {
	        /* 如果有完整的包,则添加这个包,调整各个参数 */
            try {
                // 解析出一个包
                InPacket packet = PacketHelper.proceed(receiveBuf, Packet.TCP, len);
	            addR(packet);
		        if(packet != null)
		            log.debug("已接收 - " + packet.toString());
            } catch (PacketParseException e) {
                // 如果出错,跳过这个包,读下一个
    	        receiveBuf.position(readPos + len);
            }
	        // 如果已经没有更多的数据可读,返回
            readPos += len;
	        if(readPos >= pos) break;
	        // 如果还有数据,重设读取pos,继续
	        len = receiveBuf.getChar(readPos);
	    }
	    // 如果readPos等于0,说明收到了至少一个完整的包,如果等于0,说明没有收到完整的包
	    //    根据这两种情况对buffer做出调整
	    if(readPos != 0) {
	        receiveBuf.compact();  
	        receiveBuf.limit(receiveBuf.capacity());
	        //log.debug("Compact Pos = " + receiveBuf.position());	        
	    } else {
	        receiveBuf.limit(receiveBuf.capacity());
	        receiveBuf.position(pos);	        
	    }
    }

    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.IPort#send()
     */
    public void send() throws IOException {
		while (!isEmptyS()) {
			sendBuf.clear();
			OutPacket packet = removeS();
			packet.fill(sendBuf);
			sendBuf.flip();
			if(packet.needAck()) {
			    channel.write(sendBuf);
				// 添加到重发队列
				packet.setTimeout(System.currentTimeMillis() + QQ.QQ_SENDQUEUE_TIMEOUT);
				resender.add(packet);
				log.debug("已发送 - " + packet.toString());			    
			} else {
			    for(int i = 0; i < 4; i++) {
			        sendBuf.rewind();
			        channel.write(sendBuf);
					log.debug("已发送 - " + packet.toString());
			    }
			}
		}
    }

    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.IPort#send(edu.tsinghua.lumaqq.qq.packets.OutPacket)
     */
    public void send(OutPacket packet) {
		try {
            sendBuf.clear();
            packet.fill(sendBuf);
            sendBuf.flip();
            if(packet.needAck()) {
                channel.write(sendBuf);
            	log.debug("已发送 - " + packet.toString());			    
            } else {
                for(int i = 0; i < 4; i++) {
                    sendBuf.rewind();
                    channel.write(sendBuf);
            		log.debug("已发送 - " + packet.toString());
                }
            }
        } catch (Exception e) {
        }
    }

    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.IPort#send(java.nio.ByteBuffer)
     */
    public void send(ByteBuffer buffer) {
        try {
            channel.write(buffer);
        } catch (IOException e) {
        }
    }

    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.IPort#isConnected()
     */
    public boolean isConnected() {
        return ready;
    }

    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.INIOHandler#processConnect(java.nio.channels.SelectionKey)
     */
    public void processConnect(SelectionKey sk) throws IOException {
    }

    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.INIOHandler#processRead(java.nio.channels.SelectionKey)
     */
    public void processRead(SelectionKey sk) throws IOException, PacketParseException {
        receive();
    }

    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.INIOHandler#processWrite()
     */
    public void processWrite() throws IOException {
        send();
    }
    
    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.INIOHandler#processError(java.lang.Exception)
     */
    public void processError(Exception e) {
        // TODO Auto-generated method stub

    }
}

⌨️ 快捷键说明

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