当前位置: 首页>>代码示例>>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;未经允许,请勿转载。