Java 类java.net.DatagramPacket 实例源码
项目:T0rlib4Android
文件:Socks5DatagramSocket.java
/**
* 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));
}
项目:litiengine
文件:UdpPacketReceiver.java
@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();
}
项目:java-coap
文件:MulticastSocketTransport.java
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);
}
}
}
项目:WifiChatSharing
文件:MessageActivity.java
@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;
}
项目:ServerBrowser
文件:SampQuery.java
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);
}
项目:sonos-remote-things
文件:Device.java
/**
* 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"));
}
项目:2017SteamBot2
文件:UDPReceive.java
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();
}
}
项目:thirdcoast
文件:ClientHandler.java
/**
* Start streaming the items specified in the subscription.
*
* @param subscription Items to stream to client
*/
public void start(Subscription subscription) {
if (scheduler != null) {
return;
}
logger.info("Sending graph data to {}:{}", subscription.client(), port);
socketAddress = new InetSocketAddress(subscription.client(), port);
scheduler = Executors.newSingleThreadScheduledExecutor();
// FIXME: future not checked for exception
ScheduledFuture<?> future =
scheduler.scheduleAtFixedRate(
() -> {
Buffer buffer = new Buffer();
try {
subscription.measurementsToJson(buffer);
byte[] bytes = buffer.readByteArray();
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, socketAddress);
socket.send(packet);
} catch (IOException e) {
logger.error("Exception sending grapher data", e);
}
},
0,
5,
MILLISECONDS);
}
项目:broadlink-java-api
文件:RM2Device.java
/**
* 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;
}
项目:jda-async-packetprovider
文件:AsyncPacketProvider.java
@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();
}
}
项目:OpenJSharp
文件:SnmpAdaptorServer.java
/**
* 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++;
}
项目:RISE-V2G
文件:UDPServer.java
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;
}
}
项目:cordova-plugin-smartconfig
文件:UDPSocketServer.java
/**
* 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();
}
}
项目:openjdk-jdk10
文件:RespondToRetransmit.java
@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;
}
项目:OpenJSharp
文件:SnmpRequestHandler.java
/**
* 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();
}
项目:ZooKeeper
文件:LENonTerminateTest.java
/**
* 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);
}
}
项目:NSS
文件:DataMessage.java
public void create(int timeId){
this.timeId=timeId;
dpData=new byte[this.length+16+8];
ByteShortConvert.toByteArray(ver, dpData, 0); //add: ver
ByteShortConvert.toByteArray(sType, dpData, 2); //add: service type
ByteIntConvert.toByteArray(connectId, dpData, 4); //add: sequence
ByteIntConvert.toByteArray(clientId, dpData, 8); //add: sequence
ByteIntConvert.toByteArray(this.sequence, dpData, 12); //add: sequence
ByteShortConvert.toByteArray((short) this.length, dpData, 16); //add:length
ByteIntConvert.toByteArray(this.timeId, dpData, 18); //add: sequence
System.arraycopy(this.data, 0, dpData, 22, this.length);
dp=new DatagramPacket(dpData,dpData.length);
dp.setAddress(dstAddress);
dp.setPort(dstPort);
}
项目:JDA-Audio
文件:AudioPacket.java
public static AudioPacket decryptAudioPacket(DatagramPacket packet, byte[] secretKey)
{
TweetNaclFast.SecretBox boxer = new TweetNaclFast.SecretBox(secretKey);
AudioPacket encryptedPacket = new AudioPacket(packet);
byte[] extendedNonce = new byte[XSALSA20_NONCE_LENGTH];
System.arraycopy(encryptedPacket.getNonce(), 0, extendedNonce, 0, RTP_HEADER_BYTE_LENGTH);
byte[] decryptedAudio = boxer.open(encryptedPacket.getEncodedAudio(), extendedNonce);
byte[] decryptedRawPacket = new byte[RTP_HEADER_BYTE_LENGTH + decryptedAudio.length];
System.arraycopy(encryptedPacket.getNonce(), 0, decryptedRawPacket, 0, RTP_HEADER_BYTE_LENGTH);
System.arraycopy(decryptedAudio, 0, decryptedRawPacket, RTP_HEADER_BYTE_LENGTH, decryptedAudio.length);
return new AudioPacket(decryptedRawPacket);
}
项目:openhab2-addon-hs110
文件:HS110DiscoveryService.java
private void detectThing(DatagramPacket packet) throws IOException {
String data = Util
.decrypt(new ByteArrayInputStream(Arrays.copyOfRange(packet.getData(), 0, packet.getLength())), true);
logger.debug("Detecting HS110 by data: {}", data);
String inetAddress = packet.getAddress().getHostAddress();
String id = HS110.parseDeviceId(data);
logger.debug("HS110 with id {} found on {} ", id, inetAddress);
ThingUID thingUID = new ThingUID(HS110BindingConstants.THING_TYPE_HS110, id);
String label = "HS110 at " + inetAddress;
Map<String, Object> properties = new TreeMap<>();
properties.put(HS110BindingConstants.CONFIG_IP, inetAddress);
DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withLabel(label)
.withProperties(properties).build();
thingDiscovered(discoveryResult);
}
项目:multicast
文件:TiandeMulticastSocket.java
/**
* 组播发送消息
* @param msg
*/
public void send(TiandeMulticastMessage msg){
if(cast == null){
throw new TiandeMultiCastException("Multi cast server is closed!");
}
/* 判断msg大小 */
String msgJson = msg.toString();
//base64转码
String msgBase64 = Base64.encode(msgJson);
/* 拆包发送 */
TiandeMulticastMessageManager castMessageManager = new TiandeMulticastMessageManager(msgBase64, this);
List<DatagramPacket> packetList = castMessageManager.getDatagramPacketList();
for(int i = 0; i < packetList.size(); i++){
try {
/* 休眠时间 */
Thread.sleep(intervalSend);
cast.send(packetList.get(i));
} catch (Exception e) {
e.printStackTrace();
}
}
}
项目:jdk8u-jdk
文件:SnmpAdaptorServer.java
/**
* 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++;
}
项目:myster
文件:ImmutableDatagramPacket.java
public ImmutableDatagramPacket(DatagramPacket p) {
address = p.getAddress();
port = p.getPort();
byte[] temp_data = p.getData();
int length = p.getLength();
byte[] b_temp = new byte[length];
if (length < temp_data.length) {
b_temp = new byte[length];
for (int i = 0; i < length; i++) {
b_temp[i] = temp_data[i];
}
} else if (length > temp_data.length) { //should not happen.
throw new RuntimeException(
"Length is bigger then message, packet is garbage.");
}
data = b_temp;
}
项目:OCast-Java
文件:SSDPDiscoveryTest.java
@Test
public void scanSingleResult() throws Exception {
final DatagramSocket socketMessage = mock(DatagramSocket.class);
doAnswer(new ReceiveAnswer(new String[]{GOOD_SSDP_PAYLOAD1})).when(socketMessage).receive(any(DatagramPacket.class));
FakeExecutorListener callback = Mockito.spy(new FakeExecutorListener());
SSDPDiscovery ssdp = new SSDPDiscovery("urn:cast-ocast-org:service:cast:1", 3000) {
@Override
protected DatagramSocket createSocket() {
return socketMessage;
}
};
ssdp.addListener(callback);
ssdp.start();
callback.await(3, TimeUnit.SECONDS);
verify(callback, times(1)).onLocationSent();
verify(callback, times(1)).onLocationReceived(any(SSDPMessage.class));
SSDPMessage result = callback.getResult();
assertThat(result.getUuid(), is(equalTo("c4323fee-db4b-4227-9039-fa4b71589e26")));
}
项目:messenger
文件:PeerTransmission.java
public void sendPacket(InetAddress address, int port, byte[] payload, int offset, int length) {
if (address == null)
return;
if (Looper.myLooper() == Looper.getMainLooper()) {
new Thread(() -> sendPacket(address, port, payload, offset, length));
return;
}
DatagramPacket packet = new DatagramPacket(payload, length);
packet.setAddress(address);
packet.setPort(port);
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
项目:T0rlib4j
文件:Socks5DatagramSocket.java
/**
* 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));
}
项目:maxcube-java
文件:MinaDiscoveryClientTest.java
@Test
public void testGoodCaseDiscovery() throws Exception {
int port = randomIntBetween(60000, 65000);
String data = randomAsciiOfLength(18);
try (MinaDiscoveryClient client = new MinaDiscoveryClient(port)) {
List<DiscoveredCube> cubes = new ArrayList<>();
NetworkInterface localhostInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
client.startServer(localhostInterface, cubes);
try (DatagramSocket clientSocket = new DatagramSocket()) {
clientSocket.setReuseAddress(true);
byte[] discoverBytes = data.getBytes(UTF_8);
DatagramPacket sendPacket = new DatagramPacket(discoverBytes, discoverBytes.length, InetAddress.getLocalHost(), port);
logger.info("Sending UDP packet to [{}:{}]", InetAddress.getLocalHost(), port);
clientSocket.send(sendPacket);
}
// waiting without sleeping would be better
Thread.sleep(500);
assertThat(cubes, hasSize(greaterThan(0)));
assertThat(cubes.stream().filter(cube -> cube.id.equals(data.substring(8, 18))).count(), is(1L));
}
}
项目:rtmp-rtsp-stream-client-java
文件:RtpSocketUdp.java
/**
* This RTP socket implements a buffering mechanism relying on a FIFO of buffers and a Thread.
*/
public RtpSocketUdp(ConnectCheckerRtsp connectCheckerRtsp) {
super();
this.connectCheckerRtsp = connectCheckerRtsp;
senderReportUdp = new SenderReportUdp(connectCheckerRtsp);
senderReportUdp.reset();
packets = new DatagramPacket[bufferCount];
for (int i = 0; i < bufferCount; i++) {
packets[i] = new DatagramPacket(buffers[i], 1);
}
try {
mSocket = new MulticastSocket();
} catch (IOException e) {
e.printStackTrace();
}
}
项目:Reer
文件:FileLockCommunicator.java
public void pingOwner(int ownerPort, long lockId, String displayName) {
try {
byte[] bytesToSend = encode(lockId);
// Ping the owner via all available local addresses
for (InetAddress address : addressFactory.getCommunicationAddresses()) {
socket.send(new DatagramPacket(bytesToSend, bytesToSend.length, address, ownerPort));
}
} catch (IOException e) {
throw new RuntimeException(String.format("Failed to ping owner of lock for %s (lock id: %s, port: %s)", displayName, lockId, ownerPort), e);
}
}
项目:Reer
文件:FileLockCommunicator.java
public long receive() throws GracefullyStoppedException {
try {
byte[] bytes = new byte[9];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
socket.receive(packet);
return decode(bytes);
} catch (IOException e) {
if (!stopped) {
throw new RuntimeException(e);
}
throw new GracefullyStoppedException();
}
}
项目:streaminglib
文件:RtpStream.java
@Override
public void run() {
while (!Thread.interrupted()) {
try {
byte[] buffer = new byte[MTU];
DatagramPacket p = new DatagramPacket(buffer, MTU);
rtpSocket.receive(p);
p.getLength();
streamEventBus.post(new RtspSessionEvent.RtpPacketReceived(buffer));
} catch (IOException e) {
e.printStackTrace();
}
}
}
项目:openvisualtraceroute
文件:UDP.java
private static void test() throws Exception {
final String hostname = "google.com";
final String localhost = "localhost";
final MulticastSocket datagramSocket = new MulticastSocket();
datagramSocket.setSoTimeout(10000);
short ttl = 1;
final InetAddress receiverAddress = InetAddress.getByName(hostname);
while (ttl < 100) {
try {
byte[] buffer = "0123456789".getBytes();
datagramSocket.setTimeToLive(ttl++);
final DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, receiverAddress, 80);
datagramSocket.send(sendPacket);
buffer = new byte[10];
final DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(receivePacket);
System.out.println("ttl=" + ttl + " address=" + receivePacket.getAddress().getHostAddress() + " data="
+ new String(receivePacket.getData()));
Thread.sleep(1000);
} catch (final SocketTimeoutException e) {
System.out.println("timeout ttl=" + ttl);
}
}
}
项目:NSS
文件:CloseMessage_Conn.java
public CloseMessage_Conn(int connectId,int clientId){
byte[] dpData=new byte[12];
this.clientId=clientId;
this.connectId=connectId;
ByteShortConvert.toByteArray(ver, dpData, 0);
ByteShortConvert.toByteArray(sType, dpData, 2);
ByteIntConvert.toByteArray(connectId, dpData, 4);
ByteIntConvert.toByteArray(clientId, dpData, 8);
dp=new DatagramPacket(dpData,dpData.length);
}
项目:DecompiledMinecraft
文件:LanServerDetector.java
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();
}
项目:ipack
文件:UDPTransport.java
public int receive(byte[] buf, int off, int len, int waitMillis)
throws IOException
{
socket.setSoTimeout(waitMillis);
DatagramPacket packet = new DatagramPacket(buf, off, len);
socket.receive(packet);
return packet.getLength();
}
项目:DreamSocket
文件:UDPServer.java
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6969);
DatagramPacket packet = new DatagramPacket(new byte[500], 500);
while (true){
socket.receive(packet);
System.out.println(new String(packet.getData(), 0, packet.getLength()));
socket.send(packet);
}
}
项目:sonos-remote-things
文件:SSDPClient.java
/**
* Discover any UPNP device using SSDP (Simple Service Discovery Protocol).
* @param timeout in milliseconds
* @param serviceType if null it use "ssdp:all"
* @return List of devices discovered
* @throws IOException
* @see <a href="https://en.wikipedia.org/wiki/Simple_Service_Discovery_Protocol">SSDP Wikipedia Page</a>
*/
public static List<Device> discover(int timeout, String serviceType) throws IOException {
ArrayList<Device> devices = new ArrayList<Device>();
byte[] sendData;
byte[] receiveData = new byte[1024];
/* Create the search request */
StringBuilder msearch = new StringBuilder(
"M-SEARCH * HTTP/1.1\nHost: 239.255.255.250:1900\nMan: \"ssdp:discover\"\n");
if (serviceType == null) { msearch.append("ST: ssdp:all\n"); }
else { msearch.append("ST: ").append(serviceType).append("\n"); }
/* Send the request */
sendData = msearch.toString().getBytes();
DatagramPacket sendPacket = new DatagramPacket(
sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900);
DatagramSocket clientSocket = new DatagramSocket();
clientSocket.setSoTimeout(timeout);
clientSocket.send(sendPacket);
/* Receive all responses */
while (true) {
try {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
devices.add(Device.parse(receivePacket));
}
catch (SocketTimeoutException e) { break; }
}
clientSocket.close();
return Collections.unmodifiableList(devices);
}
项目:sonos-remote-things
文件:SSDPClient.java
public static Device discoverOne(int timeout, String serviceType) throws IOException {
Device device = null;
byte[] sendData;
byte[] receiveData = new byte[1024];
/* Create the search request */
StringBuilder msearch = new StringBuilder(
"M-SEARCH * HTTP/1.1\nHost: 239.255.255.250:1900\nMan: \"ssdp:discover\"\n");
if (serviceType == null) { msearch.append("ST: ssdp:all\n"); }
else { msearch.append("ST: ").append(serviceType).append("\n"); }
/* Send the request */
sendData = msearch.toString().getBytes();
DatagramPacket sendPacket = new DatagramPacket(
sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900);
DatagramSocket clientSocket = new DatagramSocket();
clientSocket.setSoTimeout(timeout);
clientSocket.send(sendPacket);
/* Receive one response */
try {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
device = Device.parse(receivePacket);
}
catch (SocketTimeoutException e) { }
clientSocket.close();
return device;
}
项目:Transmission
文件:MessageReceiver.java
private void receiveMessage() throws IOException {
byte[] data = new byte[2048];
while (receive) {
DatagramPacket datagramPacket = new DatagramPacket(data, data.length);
receiveDatagramSocket.receive(datagramPacket);
DataResult data1 = UnPacket.getInstance().getData(datagramPacket.getData());
if (data1 != null && data1.isResult() && data1.getT().getDataType()==Packet.DATA_TYPE_MESSAGE) {
MessageHandler.getInstance().handleMessage((MessageModel) data1.getT());
}
}
}
项目:NSS
文件:CloseMessage_Conn.java
public CloseMessage_Conn(DatagramPacket dp){
this.dp=dp;
dpData=dp.getData();
ver=ByteShortConvert.toShort(dpData, 0);
sType=ByteShortConvert.toShort(dpData, 2);
connectId=ByteIntConvert.toInt(dpData, 4);
clientId=ByteIntConvert.toInt(dpData, 8);
}
项目:DecompiledMinecraft
文件:RConThreadQuery.java
/**
* Sends an auth challenge DatagramPacket to the client and adds the client to the queryClients map
*/
private void sendAuthChallenge(DatagramPacket requestPacket) throws IOException
{
RConThreadQuery.Auth rconthreadquery$auth = new RConThreadQuery.Auth(requestPacket);
this.queryClients.put(requestPacket.getSocketAddress(), rconthreadquery$auth);
this.sendResponsePacket(rconthreadquery$auth.getChallengeValue(), requestPacket);
}