本文整理匯總了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));
}
示例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();
}
示例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);
}
}
}
示例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;
}
示例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);
}
示例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"));
}
示例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();
}
}
示例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;
}
示例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();
}
}
示例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++;
}
示例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;
}
}
示例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();
}
}
示例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;
}
示例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();
}
示例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);
}
}