當前位置: 首頁>>代碼示例>>Java>>正文


Java DatagramPacket類代碼示例

本文整理匯總了Java中java.net.DatagramPacket的典型用法代碼示例。如果您正苦於以下問題:Java DatagramPacket類的具體用法?Java DatagramPacket怎麽用?Java DatagramPacket使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


DatagramPacket類屬於java.net包,在下文中一共展示了DatagramPacket類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: send

import java.net.DatagramPacket; //導入依賴的package包/類
/**
 * Sends the Datagram either through the proxy or directly depending on
 * current proxy settings and destination address. <BR>
 * 
 * <B> NOTE: </B> DatagramPacket size should be at least 10 bytes less than
 * the systems limit.
 * 
 * <P>
 * See documentation on java.net.DatagramSocket for full details on how to
 * use this method.
 * 
 * @param dp
 *            Datagram to send.
 * @throws IOException
 *             If error happens with I/O.
 */
public void send(DatagramPacket dp) throws IOException {
	// If the host should be accessed directly, send it as is.
	if (!server_mode && proxy.isDirect(dp.getAddress())) {
		super.send(dp);
		log.debug("Sending datagram packet directly:");
		return;
	}

	final byte[] head = formHeader(dp.getAddress(), 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,代碼行數:40,代碼來源:Socks5DatagramSocket.java

示例2: run

import java.net.DatagramPacket; //導入依賴的package包/類
@Override
public void run() {
  while (!this.isTerminated) {
    final byte[] data = new byte[10000];
    final DatagramPacket packet = new DatagramPacket(data, data.length);
    try {
      this.socket.receive(packet);
    } catch (final IOException e) {
      log.log(Level.SEVERE, e.getMessage(), e);
    }

    for (final IIncomingPacketObserver packetObserver : this.incomingPacketObservers) {
      packetObserver.packetReceived(packet.getData(), packet.getAddress(), packet.getPort());
    }
  }

  this.socket.close();
}
 
開發者ID:gurkenlabs,項目名稱:litiengine,代碼行數:19,代碼來源:UdpPacketReceiver.java

示例3: readingLoop

import java.net.DatagramPacket; //導入依賴的package包/類
private void readingLoop(CoapReceiver coapReceiver) {
    byte[] readBuffer = new byte[2048];

    try {
        while (true) {
            DatagramPacket datagramPacket = new DatagramPacket(readBuffer, readBuffer.length);
            mcastSocket.receive(datagramPacket);
            InetSocketAddress adr = (InetSocketAddress) datagramPacket.getSocketAddress();
            if (LOGGER.isDebugEnabled() && adr.getAddress().isMulticastAddress()) {
                LOGGER.debug("Received multicast message from: " + datagramPacket.getSocketAddress());
            }

            try {
                final CoapPacket coapPacket = CoapPacket.read(adr, datagramPacket.getData(), datagramPacket.getLength());
                receivedMessageWorker.execute(() -> coapReceiver.handle(coapPacket, TransportContext.NULL));
            } catch (CoapException e) {
                LOGGER.warn(e.getMessage());
            }
        }
    } catch (IOException ex) {
        if (!ex.getMessage().startsWith("Socket closed")) {
            LOGGER.warn(ex.getMessage(), ex);
        }
    }
}
 
開發者ID:ARMmbed,項目名稱:java-coap,代碼行數:26,代碼來源:MulticastSocketTransport.java

示例4: 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

示例5: assemblePacket

import java.net.DatagramPacket; //導入依賴的package包/類
private DatagramPacket assemblePacket(final char type) {
	final StringTokenizer tok = new StringTokenizer(server.getHostAddress(), ".");
	final StringBuffer packetData = new StringBuffer("SAMP");
	
	while (tok.hasMoreTokens()) {// The splitted parts of the ip will be parsed into ints and casted into characters
		packetData.append((char) Integer.parseInt(tok.nextToken()));
	}
	
	/*
	 * At this point the buffer contains something like 'SAMPx!2.' where each character after
	 * 'SAMP' is a part of the ip address
	 */
	
	packetData.append((char) (serverPort & 0xFF)).append((char) (serverPort >> 8 & 0xFF)).append(type);
	
	if (type == PACKET_MIRROR_CHARACTERS) {// Apply 4 random bytes, in case it was a mirror query
											// final Random random = ThreadLocalRandom.current();
											// final byte[] toMirror = new byte[4];
											// random.nextBytes(toMirror);
		packetData.append("0101"); // TODO(MSC) Fix temporarily
	}
	
	final byte[] data = packetData.toString().getBytes(StandardCharsets.US_ASCII);
	return new DatagramPacket(data, data.length, server, serverPort);
}
 
開發者ID:Bios-Marcel,項目名稱:ServerBrowser,代碼行數:26,代碼來源:SampQuery.java

示例6: parse

import java.net.DatagramPacket; //導入依賴的package包/類
/**
 * Instantiate a new Device Object from a SSDP discovery response packet.
 * @param ssdpResult SSDP Discovery Response packet.
 * @return Device
 */
public static Device parse(DatagramPacket ssdpResult) {
    HashMap<String, String> headers = new HashMap<String, String>();
    Pattern pattern = Pattern.compile("(.*): (.*)");

    String[] lines = new String(ssdpResult.getData()).split("\r\n");

    for (String line : lines) {
        Matcher matcher = pattern.matcher(line);
        if(matcher.matches()) {
            headers.put(matcher.group(1).toUpperCase(), matcher.group(2));
        }
    }

    return new Device(
            ssdpResult.getAddress().getHostAddress(),
            headers.get("LOCATION"),
            headers.get("SERVER"),
            headers.get("ST"),
            headers.get("USN"));
}
 
開發者ID:mguntli,項目名稱:sonos-remote-things,代碼行數:26,代碼來源:Device.java

示例7: UDPReceive

import java.net.DatagramPacket; //導入依賴的package包/類
public UDPReceive() {
	
	try {
		int port = 10030;

		// Create a socket to listen on the port.
		dsocket = new DatagramSocket(port);
		dsocket.setSoTimeout(2);
		
		// Create a buffer to read datagrams into.
		buffer = new byte[2048];

		// Create a packet to receive data into the buffer
		packet = new DatagramPacket(buffer, buffer.length);
	} catch (Exception e) {
		e.printStackTrace();
	}
	
}
 
開發者ID:Team997Coders,項目名稱:2017SteamBot2,代碼行數:20,代碼來源:UDPReceive.java

示例8: getTemp

import java.net.DatagramPacket; //導入依賴的package包/類
/**
 * Requests the RM2 to return the room temperature<br>
 * <br>
 * The {@link #auth() auth()} method must be ran before these commands
 * 
 * @return The room temperature in a floating number
 * @throws IOException
 *             Problems on sending packet
 */
public double getTemp() throws Exception {
    DatagramPacket packet = sendCmdPkt(new RMTempCmdPayload());
    byte[] data = packet.getData();

    int err = data[0x22] | (data[0x23] << 8);

    if (err == 0) {
        AES aes = new AES(getIv(), getKey());

        byte[] encData = BLDevice.subbytes(data, 0x38, data.length);

        encData = chgLen(encData, 1024);

        byte[] pl = aes.decrypt(encData);

        return (double) (pl[0x4] * 10 + pl[0x5]) / 10.0;
    } else {
        System.out.println(Integer.toHexString(err) + " / " + err);
    }

    return -1;
}
 
開發者ID:mob41,項目名稱:broadlink-java-api,代碼行數:32,代碼來源:RM2Device.java

示例9: run

import java.net.DatagramPacket; //導入依賴的package包/類
@Override
public void run() {
	try {
		do {
			DatagramPacket packet = AsyncPacketProvider.this.packetProvider.getNextPacket(this.changeTalking);
			if (packet == null) {
				 //actual value doesn't matter, as long as the thread gets taken out of scheduling
				Thread.sleep(40);
			} else if(!this.queue.offer(packet, 1, SECONDS) && !this.stopRequested) {
				AsyncPacketProvider.log.debug("Clock leap or something? Trying again.");
				if (!this.queue.offer(packet, 5, SECONDS) && !this.stopRequested) {
					AsyncPacketProvider.log.warn("Missed a packet, queue is not being drained. Audio send system shutdown?");
				}
			}
		} while (!this.stopRequested);
	} catch (InterruptedException ex) {
		Thread.currentThread().interrupt();
	}
}
 
開發者ID:Shredder121,項目名稱:jda-async-packetprovider,代碼行數:20,代碼來源:AsyncPacketProvider.java

示例10: sendTrapMessage

import java.net.DatagramPacket; //導入依賴的package包/類
/**
 * Send the specified message on trapSocket.
 */
private void sendTrapMessage(SnmpMessage msg)
    throws IOException, SnmpTooBigException {

    byte[] buffer = new byte[bufferSize] ;
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length) ;
    int encodingLength = msg.encodeMessage(buffer) ;
    packet.setLength(encodingLength) ;
    packet.setAddress(msg.address) ;
    packet.setPort(msg.port) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sending trap to " + msg.address + ":" +
              msg.port);
    }
    trapSocket.send(packet) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sent to " + msg.address + ":" +
              msg.port);
    }
    snmpOutTraps++;
    snmpOutPkts++;
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:27,代碼來源:SnmpAdaptorServer.java

示例11: send

import java.net.DatagramPacket; //導入依賴的package包/類
public boolean send(V2GTPMessage message, Inet6Address udpClientAddress, int udpClientPort) {
	 byte[] v2gTPMessage = message.getMessage();
	// Set up the UDP packet containing the V2GTP message to be sent to the UDP client
	DatagramPacket udpServerPacket = new DatagramPacket(v2gTPMessage, 
														v2gTPMessage.length,
														udpClientAddress,
														udpClientPort);
	
	// Send the response to the UDP client
	try {
		udpServerSocket.send(udpServerPacket);
		getLogger().debug("Message sent");
		
		return true;
	} catch (IOException e) {
		getLogger().error("UDP response failed (IOException) while trying to send message!", e);
		return false;
	}
}
 
開發者ID:V2GClarity,項目名稱:RISE-V2G,代碼行數:20,代碼來源:UDPServer.java

示例12: UDPSocketServer

import java.net.DatagramPacket; //導入依賴的package包/類
/**
 * Constructor of UDP Socket Server
 * 
 * @param port
 *            the Socket Server port
 * @param socketTimeout
 *            the socket read timeout
 * @param context
 *            the context of the Application
 */
public UDPSocketServer(int port, int socketTimeout, Context context) {
	this.mContext = context;
	this.buffer = new byte[64];
	this.mReceivePacket = new DatagramPacket(buffer, 64);
	try {
		this.mServerSocket = new DatagramSocket(port);
		this.mServerSocket.setSoTimeout(socketTimeout);
		this.mIsClosed = false;
		WifiManager manager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		mLock = manager.createMulticastLock("test wifi");
		Log.d(TAG, "mServerSocket is created, socket read timeout: "
				+ socketTimeout + ", port: " + port);
	} catch (IOException e) {
		Log.e(TAG, "IOException");
		e.printStackTrace();
	}
}
 
開發者ID:IOCare,項目名稱:cordova-plugin-smartconfig,代碼行數:29,代碼來源:UDPSocketServer.java

示例13: produceHandshakePackets

import java.net.DatagramPacket; //導入依賴的package包/類
@Override
boolean produceHandshakePackets(SSLEngine engine, SocketAddress socketAddr,
        String side, List<DatagramPacket> packets) throws Exception {

    boolean finished = super.produceHandshakePackets(
            engine, socketAddr, side, packets);

    if (needPacketDuplicate && (!(isClient ^ engine.getUseClientMode()))) {
        DatagramPacket packet = getPacket(packets, handshakeType);
        if (packet != null) {
            needPacketDuplicate = false;

            System.out.println("Duplicate the flight.");
            List<DatagramPacket> duplicates = new ArrayList<>();
            finished = super.produceHandshakePackets(
                    engine, socketAddr, side, duplicates);
            packets.addAll(duplicates);
        }
    }

    return finished;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:23,代碼來源:RespondToRetransmit.java

示例14: SnmpRequestHandler

import java.net.DatagramPacket; //導入依賴的package包/類
/**
 * Full constructor
 */
public SnmpRequestHandler(SnmpAdaptorServer server, int id,
                          DatagramSocket s, DatagramPacket p,
                          SnmpMibTree tree, Vector<SnmpMibAgent> m,
                          InetAddressAcl a,
                          SnmpPduFactory factory,
                          SnmpUserDataFactory dataFactory,
                          MBeanServer f, ObjectName n)
{
    super(server, id, f, n);

    // Need a reference on SnmpAdaptorServer for getNext & getBulk,
    // in case of oid equality (mib overlapping).
    //
    adaptor = server;
    socket = s;
    packet = p;
    root= tree;
    mibs = new Vector<>(m);
    subs= new Hashtable<>(mibs.size());
    ipacl = a;
    pduFactory = factory ;
    userDataFactory = dataFactory ;
    //thread.start();
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:28,代碼來源:SnmpRequestHandler.java

示例15: mockServer

import java.net.DatagramPacket; //導入依賴的package包/類
/**
 * MockServer plays the role of peer C. Respond to two requests for votes
 * with vote for self and then Assert.fail. 
 */
void mockServer() throws InterruptedException, IOException {          
    byte b[] = new byte[36];
    ByteBuffer responseBuffer = ByteBuffer.wrap(b);
    DatagramPacket packet = new DatagramPacket(b, b.length);
    QuorumServer server = peers.get(Long.valueOf(2));
    DatagramSocket udpSocket = new DatagramSocket(server.addr.getPort());
    LOG.info("In MockServer");
    mockLatch.countDown();
    Vote current = new Vote(2, 1);
    for (int i=0;i<2;++i) {
        udpSocket.receive(packet);
        responseBuffer.rewind();
        LOG.info("Received " + responseBuffer.getInt() + " " + responseBuffer.getLong() + " " + responseBuffer.getLong());
        LOG.info("From " + packet.getSocketAddress());
        responseBuffer.clear();
        responseBuffer.getInt(); // Skip the xid
        responseBuffer.putLong(2);
        
        responseBuffer.putLong(current.getId());
        responseBuffer.putLong(current.getZxid());
        packet.setData(b);
        udpSocket.send(packet);
    }
}
 
開發者ID:l294265421,項目名稱:ZooKeeper,代碼行數:29,代碼來源:LENonTerminateTest.java


注:本文中的java.net.DatagramPacket類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。