portcontainingpacket.java

来自「java语言开发的P2P流媒体系统」· Java 代码 · 共 94 行

JAVA
94
字号
/* 
 * P2P-Radio - Peer to peer streaming system
 * Project homepage: http://p2p-radio.sourceforge.net/
 * Copyright (C) 2003-2004 Michael Kaufmann <hallo@michael-kaufmann.ch>
 * 
 * ---------------------------------------------------------------------------
 * 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 p2pradio.packets;

public abstract class PortContainingPacket extends Packet
{
	private int port;
	
	protected PortContainingPacket(byte packetType, byte content[], int port)
	{
		super(packetType, content);
		
		portToBytes(this, port);		
		this.port = port;
	}
	
	protected PortContainingPacket(byte content[], int contentLength)
	{
		super(content, contentLength);
		
		port = bytesToPort(this);
	}
		
	protected int getPort()
	{
		return port;
	}
	
	protected static void portToBytes(Packet packet, int port)
	{
		//A port number has 2 Bytes
		// Eine Portnummer hat 2 Bytes
		packet.checkBytesLeft(2);
		
		// Port als 2 einzelne Bytes speichern
		// Siehe DataOutputStream.java
		//Convert the int port into 2 bytes using binary shifting and binary AND
		packet.content[packet.offset + 0] = (byte)((port >>> 8) & 0xFF); 
		packet.content[packet.offset + 1] = (byte)((port >>> 0) & 0xFF);
		
		packet.offset += 2;
	}
	
	protected static int bytesToPort(Packet packet)
	{
		// Eine Portnummer hat 2 Bytes
		packet.checkBytesLeft(2);
		
		// Port-Nummer lesen
		// Siehe DataInputStream.java
		int ch1 = (packet.content[packet.offset + 0] & 0xff);
		int ch2 = (packet.content[packet.offset + 1] & 0xff);
		
		int port = ((ch1 << 8) + (ch2 << 0));
		
		packet.offset += 2;
		
		// Das ist gar nicht mehr m鰃lich ;-)
		/*
		if ((port < 0) || (port > 65535))
		{
			throw new IllegalArgumentException("Port-Nummer ist ausserhalb des zul鋝sigen Bereichs");
		}
		*/
		
		return port;
	}
	
	protected static int getMaxLength()
	{
		return Packet.getMaxLength() + 2;
	}
}

⌨️ 快捷键说明

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