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

📄 tcpport.java

📁 用java实现的
💻 JAVA
字号:
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004  notXX
*                     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.packets.InPacket;
import edu.tsinghua.lumaqq.qq.packets.OutPacket;
import edu.tsinghua.lumaqq.qq.packets.Packet;
import edu.tsinghua.lumaqq.qq.packets.PacketHelper;

/**
 * 利用TCP端口通信的QQ端口. 
 * 因为TCP传送的是数据流而不是数据包, 所以QQ数据包的头部有两个字节记录了这个数据包的长度.
 * 相应的, 基于TCP的QQ端口也必须处理这种情况. 我们不能保证一个数据包的数据是在同一时间来到的, 所以必须考虑把多次到来的一个数据包拼凑起来.
 * 
 * @author notxx
 * @author 马若劼
 */
public final class TCPPort extends AbstractPort implements INIOHandler {
    /** Log类 */
	private static final Log log = LogFactory.getLog(TCPPort.class);
	/** 用于通信的channel */
	private final SocketChannel channel;
	
	/**
	 * 构造一个连接到指定地址的TCPPort. 
	 * 
	 * @param address 连接到的地址.
	 * @throws IOException 端口打开/端口配置/连接到地址出错.
	 */
	public TCPPort(InetSocketAddress address) throws IOException {
		channel = SocketChannel.open();
		channel.configureBlocking(false);
		channel.connect(address);
		porter.register(channel);
		porter.setNIOHandler(this);
	}

	/* (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.AbstractPort#dispose()
     */
    public void dispose() throws IOException {
        super.dispose();
        channel.close();
    }
    
    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.IPort#isConnected()
     */
    public boolean isConnected() {
        return channel != null && channel.isConnected();
    }
    
    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.IHandler#processConnect(java.nio.channels.SelectionKey)
     */
    public void processConnect(SelectionKey sk) throws IOException {
        //完成SocketChannel的连接
        channel.finishConnect();
        while(!channel.isConnected()) {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
            }            
            channel.finishConnect();
        }
    	sk.interestOps(SelectionKey.OP_READ);
    	log.debug("已连接上QQ服务器");
    }

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

    /* (non-Javadoc)
     * @see edu.tsinghua.lumaqq.qq.IHandler#processWrite()
     */
    public void processWrite() throws IOException {
        if(isConnected())
            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 + -