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

📄 tcpconnection.java

📁 封装了SQL、Socket、WAP、MIME等功能的通用组件
💻 JAVA
字号:
/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */
package org.lazybug.net;

import org.lazybug.util.*;
import java.io.*;
import java.net.*;

public class TCPConnection extends Connection
{
    private int bufferLength = 0;
    public Socket socket;
    private DataInputStream in;
    private DataOutputStream out;

    public TCPConnection(Socket s, int nPageNum, int nPageSize) throws IOException
    {
        super(nPageNum, nPageSize);
        this.bufferLength = this.pageNum * this.pageSize;
        super.buffer = new byte[bufferLength];
        this.socket = s;
        this.in = new DataInputStream(this.socket.getInputStream());
        this.out = new DataOutputStream(this.socket.getOutputStream());
    }

    public int getMaxPageLength() {
        return this.pageSize;
    }

    public int getBufferLength() {
        return bufferLength;
    }

    /**
     * 实现了Connection的接口,接收数据包
     * @param packet
     * @return
     * @throws java.io.IOException
     */
    public int onReceiveFrom(Packet packet) throws java.io.IOException
    {
        int n = 0;
        if( (n=in.read(buffer, packet.offset, 2)) == -1 ){
            throw  new java.io.IOException("读写通道被关闭了!");
        }
        int length = Tools.bytesToInt(buffer, packet.offset, 2);
        if (length > pageSize ||   length < packet.getHeaderMaxLength())
        {
            Log.logWarning(this, "未知数据包[包长" + length + "][规格" + pageSize + "]");
            throw new UnknowPacketException();
        }

        int size = length - 2;
        int index = packet.offset + 2;
        while (size > 0) {
            int l = in.read(buffer, index, size);
            if( l == - 1 ){
                throw  new java.io.IOException("读写通道被关闭了!");
            }

            if (l > 0) {
                size -= l;
                index += l;
            }
        }
        return length;
    }

    /**
     * 通过输出流发送数据包
     * @param packet
     * @return
     * @throws java.io.IOException
     */
    public int onSendTo(Packet packet) throws java.io.IOException {
        out.write(buffer, packet.buffer_offset, packet.getLength());
        return packet.getLength();
    }

    public void close() {
        try {
            this.out.close();
            this.in.close();
            this.socket.close();
        }
        catch (IOException e) {}
    }

    public String getIPAndPort() {
        return this.socket.getInetAddress().getHostAddress() + ":" +
            this.socket.getPort();
    }

    public int getIP() {
        return Tools.bytesToInt(this.socket.getInetAddress().getAddress());
    }

    public int getPort() {
        return this.socket.getPort();
    }

}

⌨️ 快捷键说明

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