当前位置: 首页>>代码示例>>Java>>正文


Java DatagramPacket.getLength方法代码示例

本文整理汇总了Java中java.net.DatagramPacket.getLength方法的典型用法代码示例。如果您正苦于以下问题:Java DatagramPacket.getLength方法的具体用法?Java DatagramPacket.getLength怎么用?Java DatagramPacket.getLength使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.net.DatagramPacket的用法示例。


在下文中一共展示了DatagramPacket.getLength方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: UDPEchoTest

import java.net.DatagramPacket; //导入方法依赖的package包/类
private static void UDPEchoTest() throws IOException {
    DatagramChannel dc = Launcher.launchWithDatagramChannel(ECHO_SERVICE, null);

    String msg = "I was out saving the galaxy when your grandfather was in diapers";

    ByteBuffer bb = ByteBuffer.wrap(msg.getBytes("UTF-8"));
    dc.write(bb);

    // and receive the echo
    byte b[] = new byte[msg.length() + 100];
    DatagramPacket pkt2 = new DatagramPacket(b, b.length);
    dc.socket().setSoTimeout(5000);
    dc.socket().receive(pkt2);

    if (pkt2.getLength() != msg.length()) {
        throw new RuntimeException("Received packet of incorrect length");
    }

    dc.close();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:EchoTest.java

示例2: doInBackground

import java.net.DatagramPacket; //导入方法依赖的package包/类
@Override
protected Boolean doInBackground(Void... voids) {

    Thread newThread = new Thread() {

        public void run() {
            while (true) {
                byte[] recvPkt = new byte[1024];
                DatagramPacket recv = new DatagramPacket(recvPkt, recvPkt.length);
                try {
                    socket.receive(recv);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                final String medd = new String(recvPkt, 0, recv.getLength());
                recQue.add(medd);
                updateListView(medd);
            }
        }
    };
    newThread.start();
    return null;
}
 
开发者ID:yuvaraj119,项目名称:WifiChatSharing,代码行数:25,代码来源:MessageActivity.java

示例3: run

import java.net.DatagramPacket; //导入方法依赖的package包/类
public void run() {
    try {
        System.err.println("started server thread: " + server);
        byte[] buf = new byte[1024];
        DatagramPacket receivePacket = new DatagramPacket(buf,
                                                          buf.length);
        server.receive(receivePacket);
        int len = receivePacket.getLength();
        switch(len) {
        case packetLength:
            System.out.println("receive length is: " + len);
            break;
        default:
            throw new RuntimeException(
                "receive length is: " + len +
                ", send length: " + packetLength +
                ", buffer length: " + buf.length);
        }
        return;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("caugth: " + e);
    } finally {
        if (server != null) { server.close(); }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:27,代码来源:SendSize.java

示例4: send

import java.net.DatagramPacket; //导入方法依赖的package包/类
/**
 * This method allows to send datagram packets with address type DOMAINNAME.
 * SOCKS5 allows to specify host as names rather than ip addresses.Using
 * this method one can send udp datagrams through the proxy, without having
 * to know the ip address of the destination host.
 * <p>
 * If proxy specified for that socket has an option resolveAddrLocally set
 * to true host will be resolved, and the datagram will be send with address
 * type IPV4, if resolve fails, UnknownHostException is thrown.
 * 
 * @param dp
 *            Datagram to send, it should contain valid port and data
 * @param host
 *            Host name to which datagram should be send.
 * @throws IOException
 *             If error happens with I/O, or the host can't be resolved when
 *             proxy settings say that hosts should be resolved locally.
 * @see Socks5Proxy#resolveAddrLocally(boolean)
 */
public void send(DatagramPacket dp, String host) throws IOException {
	if (proxy.isDirect(host)) {
		dp.setAddress(InetAddress.getByName(host));
		super.send(dp);
		return;
	}

	if ((proxy).resolveAddrLocally) {
		dp.setAddress(InetAddress.getByName(host));
	}

	final byte[] head = formHeader(host, dp.getPort());
	byte[] buf = new byte[head.length + dp.getLength()];
	final byte[] data = dp.getData();
	// Merge head and data
	System.arraycopy(head, 0, buf, 0, head.length);
	// System.arraycopy(data,dp.getOffset(),buf,head.length,dp.getLength());
	System.arraycopy(data, 0, buf, head.length, dp.getLength());

	if (encapsulation != null) {
		buf = encapsulation.udpEncapsulate(buf, true);
	}

	super.send(new DatagramPacket(buf, buf.length, relayIP, relayPort));
}
 
开发者ID:PanagiotisDrakatos,项目名称:T0rlib4Android,代码行数:45,代码来源:Socks5DatagramSocket.java

示例5: run

import java.net.DatagramPacket; //导入方法依赖的package包/类
@Override
public void run() {
	while (true) {
		DatagramPacket packet = new DatagramPacket(receive_str_byte, receive_str_byte.length);
		try {
			client.getDs().receive(packet);
			InetAddress address = packet.getAddress();
			int port = packet.getPort();
			int len = packet.getLength();
			byte[] data = packet.getData();

			System.out.printf("Request from %s Port %d:%n%s%n", address, port,
					new String(data, 0, len));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
 
开发者ID:magcode,项目名称:sunricher-wifi-mqtt,代码行数:20,代码来源:UDPListener.java

示例6: checkValidPacket

import java.net.DatagramPacket; //导入方法依赖的package包/类
public static boolean checkValidPacket(DatagramPacket packet, boolean macSequence) {
	byte[] data;
	boolean correct = false;
	int packetLength = packet.getLength();
	InfoCollector collector = new InfoCollector();
	collector.collect();
	String localMAC;
	if (macSequence)
		localMAC = collector.getMAC();
	else
		localMAC = collector.getRMAC();
	String inputMAC = getInputMAC(packet);
	final String WOLHEAD = "FF:FF:FF:FF:FF:FF";
	final int WOL_LENGTH = 108;
	
	if (packetLength > WOL_LENGTH)
		return false;
	else if (packetLength > 0){
		data = packet.getData();
		if (hexConvert(data, true).substring(0, 16).equals(WOLHEAD))
			correct = false;
		else if (checkValidMAC(inputMAC) == false)
			correct = false;
		else if (!localMAC.equals(inputMAC))
			correct = false;
		else
			correct = true;
	}
	return correct;
}
 
开发者ID:ivangundampc,项目名称:SleepOnLan,代码行数:31,代码来源:MagicPacket.java

示例7: send

import java.net.DatagramPacket; //导入方法依赖的package包/类
@Override
public void send(DatagramPacket p) throws IOException {
  // capture the byte arrays
  byte[] bytes = new byte[p.getLength()];
  System.arraycopy(p.getData(), p.getOffset(), bytes, 0, p.getLength());
  capture.add(bytes);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:8,代码来源:TestGangliaMetrics.java

示例8: run

import java.net.DatagramPacket; //导入方法依赖的package包/类
public void run()
{
    byte[] abyte = new byte[1024];

    while (!this.isInterrupted())
    {
        DatagramPacket datagrampacket = new DatagramPacket(abyte, abyte.length);

        try
        {
            this.socket.receive(datagrampacket);
        }
        catch (SocketTimeoutException var5)
        {
            continue;
        }
        catch (IOException ioexception)
        {
            LanServerDetector.logger.error((String)"Couldn\'t ping server", (Throwable)ioexception);
            break;
        }

        String s = new String(datagrampacket.getData(), datagrampacket.getOffset(), datagrampacket.getLength());
        LanServerDetector.logger.debug(datagrampacket.getAddress() + ": " + s);
        this.localServerList.func_77551_a(s, datagrampacket.getAddress());
    }

    try
    {
        this.socket.leaveGroup(this.broadcastAddress);
    }
    catch (IOException var4)
    {
        ;
    }

    this.socket.close();
}
 
开发者ID:Notoh,项目名称:DecompiledMinecraft,代码行数:39,代码来源:LanServerDetector.java

示例9: run

import java.net.DatagramPacket; //导入方法依赖的package包/类
public void run()
{
    byte[] abyte = new byte[1024];

    while (!this.isInterrupted())
    {
        DatagramPacket datagrampacket = new DatagramPacket(abyte, abyte.length);

        try
        {
            this.socket.receive(datagrampacket);
        }
        catch (SocketTimeoutException var5)
        {
            continue;
        }
        catch (IOException ioexception)
        {
            LanServerDetector.LOGGER.error((String)"Couldn\'t ping server", (Throwable)ioexception);
            break;
        }

        String s = new String(datagrampacket.getData(), datagrampacket.getOffset(), datagrampacket.getLength());
        LanServerDetector.LOGGER.debug("{}: {}", new Object[] {datagrampacket.getAddress(), s});
        this.localServerList.addServer(s, datagrampacket.getAddress());
    }

    try
    {
        this.socket.leaveGroup(this.broadcastAddress);
    }
    catch (IOException var4)
    {
        ;
    }

    this.socket.close();
}
 
开发者ID:sudofox,项目名称:Backmemed,代码行数:39,代码来源:LanServerDetector.java

示例10: run

import java.net.DatagramPacket; //导入方法依赖的package包/类
@Override
public void run() {
	String inputMAC;
   	byte[] buf = new byte[bufSize];
   	server.logNewMsg(SolServer.server.getCurrentTime() + "Listening to port " + socketPort + " with " + bufSize + " bytes buffer.");
   	commander = new Commander();

   	while(keepRunning.get()){
   		DatagramPacket packet = new DatagramPacket(buf, buf.length);
   		inputMAC = "";
   		
   		try {
   			socket = null;
   			createSocket(socketPort);
   			socket.receive(packet);
   			if (packet.getLength() < 1){
   				server.logNewMsg(SolServer.server.getCurrentTime() + "Throw error packet.");
   				continue;
   			}
   			
       		inputMAC = MagicPacket.getInputMAC(packet);
       		if (MagicPacket.checkValidPacket(packet, macSequence) && keepRunning.get() != false){
       			server.logNewMsg(SolServer.server.getCurrentTime() + "Correct MAC: " + inputMAC);
       			commander.run(cmd);
       		} else if (keepRunning.get() != false){
       			server.logNewMsg(SolServer.server.getCurrentTime() + "Incorrect MAC: " + inputMAC);
       		}
       		
       		socket.close();
   		} catch (IOException e) {
   			server.logNewMsg(SolServer.server.getCurrentTime() + "Stop listening.");
   		} 
   	}
}
 
开发者ID:ivangundampc,项目名称:SleepOnLan,代码行数:35,代码来源:Looper.java

示例11: parseIncomingPacket

import java.net.DatagramPacket; //导入方法依赖的package包/类
/**
 * Parses an incoming DatagramPacket, returning true if the packet was valid
 */
private boolean parseIncomingPacket(DatagramPacket requestPacket) throws IOException
{
    byte[] abyte = requestPacket.getData();
    int i = requestPacket.getLength();
    SocketAddress socketaddress = requestPacket.getSocketAddress();
    this.logDebug("Packet len " + i + " [" + socketaddress + "]");

    if (3 <= i && -2 == abyte[0] && -3 == abyte[1])
    {
        this.logDebug("Packet \'" + RConUtils.getByteAsHexString(abyte[2]) + "\' [" + socketaddress + "]");

        switch (abyte[2])
        {
            case 0:

                if (!this.verifyClientAuth(requestPacket).booleanValue())
                {
                    this.logDebug("Invalid challenge [" + socketaddress + "]");
                    return false;
                }
                else if (15 == i)
                {
                    this.sendResponsePacket(this.createQueryResponse(requestPacket), requestPacket);
                    this.logDebug("Rules [" + socketaddress + "]");
                }
                else
                {
                    RConOutputStream rconoutputstream = new RConOutputStream(1460);
                    rconoutputstream.writeInt(0);
                    rconoutputstream.writeByteArray(this.getRequestID(requestPacket.getSocketAddress()));
                    rconoutputstream.writeString(this.serverMotd);
                    rconoutputstream.writeString("SMP");
                    rconoutputstream.writeString(this.worldName);
                    rconoutputstream.writeString(Integer.toString(this.getNumberOfPlayers()));
                    rconoutputstream.writeString(Integer.toString(this.maxPlayers));
                    rconoutputstream.writeShort((short)this.serverPort);
                    rconoutputstream.writeString(this.queryHostname);
                    this.sendResponsePacket(rconoutputstream.toByteArray(), requestPacket);
                    this.logDebug("Status [" + socketaddress + "]");
                }

            default:
                return true;
            case 9:
                this.sendAuthChallenge(requestPacket);
                this.logDebug("Challenge [" + socketaddress + "]");
                return true;
        }
    }
    else
    {
        this.logDebug("Invalid packet [" + socketaddress + "]");
        return false;
    }
}
 
开发者ID:F1r3w477,项目名称:CustomWorldGen,代码行数:59,代码来源:RConThreadQuery.java

示例12: receive

import java.net.DatagramPacket; //导入方法依赖的package包/类
/**
 * Receives udp packet. If packet have arrived from the proxy relay server,
 * it is processed and address and port of the packet are set to the address
 * and port of sending host.<BR>
 * If the packet arrived from anywhere else it is not changed.<br>
 * <B> NOTE: </B> DatagramPacket size should be at least 10 bytes bigger
 * than the largest packet you expect (this is for IPV4 addresses). For
 * hostnames and IPV6 it is even more.
 * 
 * @param dp
 *            Datagram in which all relevent information will be copied.
 */
public void receive(DatagramPacket dp) throws IOException {
	super.receive(dp);

	if (server_mode) {
		// Drop all datagrams not from relayIP/relayPort
		final int init_length = dp.getLength();
		final int initTimeout = getSoTimeout();
		final long startTime = System.currentTimeMillis();

		while (!relayIP.equals(dp.getAddress())
				|| (relayPort != dp.getPort())) {

			// Restore datagram size
			dp.setLength(init_length);

			// If there is a non-infinit timeout on this socket
			// Make sure that it happens no matter how often unexpected
			// packets arrive.
			if (initTimeout != 0) {
				final long passed = System.currentTimeMillis() - startTime;
				final int newTimeout = initTimeout - (int) passed;

				if (newTimeout <= 0) {
					throw new InterruptedIOException(
							"In Socks5DatagramSocket->receive()");
				}
				setSoTimeout(newTimeout);
			}

			super.receive(dp);
		}

		// Restore timeout settings
		if (initTimeout != 0) {
			setSoTimeout(initTimeout);
		}

	} else if (!relayIP.equals(dp.getAddress())
			|| (relayPort != dp.getPort())) {
		return; // Recieved direct packet
		// If the datagram is not from the relay server, return it it as is.
	}

	byte[] data;
	data = dp.getData();

	if (encapsulation != null) {
		data = encapsulation.udpEncapsulate(data, false);
	}

	// FIXME: What is this?
	final int offset = 0; // Java 1.1
	// int offset = dp.getOffset(); //Java 1.2

	final ByteArrayInputStream bIn = new ByteArrayInputStream(data, offset,
			dp.getLength());

	final ProxyMessage msg = new Socks5Message(bIn);
	dp.setPort(msg.port);
	dp.setAddress(msg.getInetAddress());

	// what wasn't read by the Message is the data
	final int data_length = bIn.available();
	// Shift data to the left
	System.arraycopy(data, offset + dp.getLength() - data_length, data,
			offset, data_length);

	dp.setLength(data_length);
}
 
开发者ID:PanagiotisDrakatos,项目名称:T0rlib4Android,代码行数:82,代码来源:Socks5DatagramSocket.java

示例13: executeDiscovery

import java.net.DatagramPacket; //导入方法依赖的package包/类
private void executeDiscovery() {
    try {
        final InetAddress inetAddress = InetAddress.getByName(MCAST_GROUP);
        final byte[] datagramBuffer = new byte[512];

        discoverySocket = new MulticastSocket(DISCOVERY_SOCKET_PORT);
        discoverySocket.setSoTimeout(0);
        discoverySocket.setReuseAddress(true);
        discoverySocket.joinGroup(inetAddress);

        while (!Thread.currentThread().isInterrupted()) {
            final DatagramPacket recv = new DatagramPacket(datagramBuffer, datagramBuffer.length);

            discoverySocket.receive(recv);

            final String responseMessage = new String(recv.getData(), recv.getOffset(), recv.getLength());
            final ZMoteDevice zmoteDevice = parseDiscoveryResponse(responseMessage);

            if (zmoteDevice != null) {
                discoveryResults.put(zmoteDevice.getUuid(), new ZMoteDiscoveryResult(zmoteDevice));
                notifyDiscovery(zmoteDevice);

                if (logger.isDebugEnabled()) {
                    logger.debug("Discovered ZMote device: {}", zmoteDevice.toString());
                }

            } else if (logger.isDebugEnabled()) {
                logger.debug("Discovered unsupported device: {}", responseMessage);
            }
        }
    } catch (final Exception e) {
        if ((e instanceof SocketException) && Thread.currentThread().isInterrupted()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Discovery service worker has been terminated.");
            }
        } else if (logger.isWarnEnabled()) {
            logger.warn("ZMote device discovery failed!", e);
        }
    } finally {
        safeCloseDiscoverySocket();
    }
}
 
开发者ID:alexmaret,项目名称:openhab-binding-zmote,代码行数:43,代码来源:ZMoteDiscoveryService.java

示例14: call

import java.net.DatagramPacket; //导入方法依赖的package包/类
@Override
public Integer call() {
	isRunning.set(true);

	Set<Integer> packetReceived = new TreeSet<>();
	
	try {
		while (isRunning.get()) {
			byte[] buffer = new byte[BUFFER_LENGTH];
			DatagramPacket dp = new DatagramPacket(buffer, BUFFER_LENGTH);
			
			socket.receive(dp);
			receivedPackets++;
			byte[] data = dp.getData();
			
			//check udp packet:
			if (data[0] != UDP_IN_TEST_IDENTIFIER) {
				throw new IOException("bad UDP IN TEST identifier");
			}

			//check for duplicate packets:
			int packetNumber = data[1];
			if (packetReceived.contains(packetNumber)) {
				throw new IOException("duplicate UDP IN TEST packet");
			}
			
			
			char[] uuid = new char[dp.getLength() - 2];
			for (int i = 2; i < dp.getLength(); i++) {
				uuid[i-2] = (char) data[i];
			}
			
			if (TestServer.serverPreferences.getVerboseLevel() >= 1) {
				TestServerConsole.log("received UDP from: " + dp.getAddress().toString() + ", #" + packetNumber + ", uuid: " + String.valueOf(uuid), 1, TestServerServiceEnum.UDP_SERVICE);
			}

			//received enough packets? exit loop
			if (receivedPackets >= numPackets) {
				break;
			}
		}		
	} 
	catch (Exception e) {
		e.printStackTrace();
	}
	finally {
		if (!socket.isClosed()) {
			socket.close();
		}
	}
	
	TestServerConsole.log("UdpServer shutdown on port: " + socket.getPort(), 0, TestServerServiceEnum.UDP_SERVICE);
	return new Integer(receivedPackets);
}
 
开发者ID:rtr-nettest,项目名称:open-rmbt,代码行数:55,代码来源:UdpSingleClientServer.java

示例15: parseIncomingPacket

import java.net.DatagramPacket; //导入方法依赖的package包/类
/**
 * Parses an incoming DatagramPacket, returning true if the packet was valid
 */
private boolean parseIncomingPacket(DatagramPacket requestPacket) throws IOException
{
    byte[] abyte = requestPacket.getData();
    int i = requestPacket.getLength();
    SocketAddress socketaddress = requestPacket.getSocketAddress();
    this.logDebug("Packet len " + i + " [" + socketaddress + "]");

    if (3 <= i && -2 == abyte[0] && -3 == abyte[1])
    {
        this.logDebug("Packet \'" + RConUtils.getByteAsHexString(abyte[2]) + "\' [" + socketaddress + "]");

        switch (abyte[2])
        {
            case 0:
                if (!this.verifyClientAuth(requestPacket).booleanValue())
                {
                    this.logDebug("Invalid challenge [" + socketaddress + "]");
                    return false;
                }
                else if (15 == i)
                {
                    this.sendResponsePacket(this.createQueryResponse(requestPacket), requestPacket);
                    this.logDebug("Rules [" + socketaddress + "]");
                }
                else
                {
                    RConOutputStream rconoutputstream = new RConOutputStream(1460);
                    rconoutputstream.writeInt(0);
                    rconoutputstream.writeByteArray(this.getRequestID(requestPacket.getSocketAddress()));
                    rconoutputstream.writeString(this.serverMotd);
                    rconoutputstream.writeString("SMP");
                    rconoutputstream.writeString(this.worldName);
                    rconoutputstream.writeString(Integer.toString(this.getNumberOfPlayers()));
                    rconoutputstream.writeString(Integer.toString(this.maxPlayers));
                    rconoutputstream.writeShort((short)this.serverPort);
                    rconoutputstream.writeString(this.queryHostname);
                    this.sendResponsePacket(rconoutputstream.toByteArray(), requestPacket);
                    this.logDebug("Status [" + socketaddress + "]");
                }

            default:
                return true;

            case 9:
                this.sendAuthChallenge(requestPacket);
                this.logDebug("Challenge [" + socketaddress + "]");
                return true;
        }
    }
    else
    {
        this.logDebug("Invalid packet [" + socketaddress + "]");
        return false;
    }
}
 
开发者ID:Notoh,项目名称:DecompiledMinecraft,代码行数:59,代码来源:RConThreadQuery.java


注:本文中的java.net.DatagramPacket.getLength方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。