本文整理汇总了Java中java.net.DatagramSocket类的典型用法代码示例。如果您正苦于以下问题:Java DatagramSocket类的具体用法?Java DatagramSocket怎么用?Java DatagramSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DatagramSocket类属于java.net包,在下文中一共展示了DatagramSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: SnmpRequestHandler
import java.net.DatagramSocket; //导入依赖的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();
}
示例2: scanSingleResult
import java.net.DatagramSocket; //导入依赖的package包/类
@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")));
}
示例3: answer
import java.net.DatagramSocket; //导入依赖的package包/类
@Override
public DatagramSocket answer(InvocationOnMock invocation) throws Throwable {
//if needed, the Socket can be retrieved with:
//DatagramSocket socket = (DatagramSocket) invocation.getMock();
int timeout = 5000;
Object[] args = invocation.getArguments();
if (mCount < mResponseToSend) {
Thread.sleep(timeout/2);
((DatagramPacket) args[0]).setData(mAnswers[mCount].getBytes());
mCount++;
return null;
} else {
Thread.sleep(timeout);
throw new InterruptedIOException();
}
}
示例4: getPrimaryAddress
import java.net.DatagramSocket; //导入依赖的package包/类
/**
* For multihomed machines (i.e. anything with Docker Machine), use the
* routing table default route to find what should be the primary network
* facing interface.
* @return an InetAddress for the primary address
*/
public static InetAddress getPrimaryAddress()
{
InetAddress ret;
try {
DatagramSocket s = new DatagramSocket();
s.connect(InetAddress.getByAddress(new byte[]{1,1,1,1}), 0);
ret = s.getLocalAddress();
s.close();
return ret;
} catch (SocketException | UnknownHostException se) {
log.info("get by route failed: " + se);
}
try {
return InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
log.info("getLocalHost failed: " + ex);
}
return InetAddress.getLoopbackAddress();
}
示例5: testScanWithWrongST
import java.net.DatagramSocket; //导入依赖的package包/类
@Test
public void testScanWithWrongST() throws Exception {
final DatagramSocket socketMessage = mock(DatagramSocket.class);
doAnswer(new ReceiveAnswer(new String[]{GOOD_SSDP_PAYLOAD1})).when(socketMessage).receive(Mockito.any(DatagramPacket.class));
FakeExecutorListener callback = Mockito.spy(new FakeExecutorListener());
SSDPDiscovery ssdp = new SSDPDiscovery("urn:dummy:service:vucast: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(0)).onLocationReceived(any(SSDPMessage.class));
}
示例6: UDPTransport
import java.net.DatagramSocket; //导入依赖的package包/类
public UDPTransport(DatagramSocket socket, int mtu)
throws IOException
{
if (!socket.isBound() || !socket.isConnected())
{
throw new IllegalArgumentException("'socket' must be bound and connected");
}
this.socket = socket;
// NOTE: As of JDK 1.6, can use NetworkInterface.getMTU
this.receiveLimit = mtu - MIN_IP_OVERHEAD - UDP_OVERHEAD;
this.sendLimit = mtu - MAX_IP_OVERHEAD - UDP_OVERHEAD;
}
示例7: receiveBroadcast
import java.net.DatagramSocket; //导入依赖的package包/类
private void receiveBroadcast(DatagramSocket datagramSocket) throws IOException {
byte[] data = new byte[2048];
while (receive) {
DatagramPacket datagramPacket = new DatagramPacket(data, data.length);
datagramSocket.receive(datagramPacket);
DataResult data1 = UnPacket.getInstance().getData(datagramPacket.getData());
if (data1 != null && data1.isResult() && data1.getT().getDataType()==Packet.DATA_TYPE_ONLINE) {
// data1.getType()
// TLog.e(data1.toString());
if (listener != null) {
listener.receiver(data1);
}
}
// String s = new String(datagramPacket.getData());
//// TLog.e("address : " + datagramPacket.getAddress() + ", port : " + datagramPacket.getPort() + ", content : " + s);
// if (listener!=null){
// listener.receiver(s);
// }
}
}
示例8: jButtonDetenerActionPerformed
import java.net.DatagramSocket; //导入依赖的package包/类
private void jButtonDetenerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDetenerActionPerformed
try {
// Se intenta conectar, retorna IOException en caso que no pueda
DatagramSocket clienteSocket = new DatagramSocket();
byte[] bufferOut = new byte[1000];
String mensajeAMandar = "Mata server" + id;
bufferOut = mensajeAMandar.getBytes();
IPServer = InetAddress.getByName(servidor);
DatagramPacket sendPacket = new DatagramPacket(bufferOut, bufferOut.length, IPServer, numeroPuerto);
clienteSocket.send(sendPacket);
jLabel1.setForeground(Color.red);
clienteSocket.close();
url.setText("");
jlabelSQL.setText("");
this.setTitle("App [ID:?]");
} catch (IOException ex) {
System.out.println("(LOG) [ERROR] No se pudo contactar al servidor");
Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
}
}
示例9: getIp
import java.net.DatagramSocket; //导入依赖的package包/类
public static String getIp() {
IOException e;
try {
DatagramSocket socket = new DatagramSocket();
try {
socket.connect(InetAddress.getByName("114.114.114.114"), 53);
InetAddress local = socket.getLocalAddress();
socket.close();
return local.getHostAddress();
} catch (IOException e2) {
e = e2;
DatagramSocket datagramSocket = socket;
e.printStackTrace();
return "";
}
} catch (IOException e3) {
e = e3;
e.printStackTrace();
return "";
}
}
示例10: BLDevice
import java.net.DatagramSocket; //导入依赖的package包/类
/**
* Constructs a <code>BLDevice</code>, with a device type (constants),
* hostname and MAC address
*
* @param deviceType
* Device type constants (<code>BLDevice.DEV_*</code>)
* @param devDesc
* Friendly device description
* @param host
* Hostname of target Broadlink device
* @param mac
* MAC address of target Broadlink device
* @throws IOException
* Problems on constructing a datagram socket
*/
protected BLDevice(short deviceType, String deviceDesc, String host, Mac mac) throws IOException {
key = INITIAL_KEY;
iv = INITIAL_IV;
id = new byte[] { 0, 0, 0, 0 };
pktCount = new Random().nextInt(0xffff);
// pktCount = 0;
this.deviceType = deviceType;
this.deviceDesc = deviceDesc;
this.host = host;
this.mac = mac;
sock = new DatagramSocket(0);
sock.setReuseAddress(true);
sock.setBroadcast(true);
}
示例11: mockServer
import java.net.DatagramSocket; //导入依赖的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);
}
}
示例12: sendingCoapWithTrafficClass
import java.net.DatagramSocket; //导入依赖的package包/类
@Test
public void sendingCoapWithTrafficClass() throws Exception {
final DatagramSocket socket = spy(new QoSDatagramSocket(new InetSocketAddress(0)));
DatagramSocketTransport trans = spy(createDatagramSocketTransport());
when(trans.createSocket()).thenReturn(socket);
CoapClient client = CoapClientBuilder.newBuilder(5683).transport(trans).timeout(10000).build();
client.resource("/test").context(TrafficClassTransportContext.create(TrafficClassTransportContext.HIGH, TransportContext.NULL)).get();
verify(socket).setTrafficClass(TrafficClassTransportContext.HIGH);
verify(socket).setTrafficClass(0);
reset(socket);
client.resource("/test").get();
verify(socket, never()).setTrafficClass(anyInt());
client.close();
}
示例13: starter
import java.net.DatagramSocket; //导入依赖的package包/类
private void starter(QuorumPeer self) {
this.self = self;
port = self.getVotingView().get(self.getId()).electionAddr.getPort();
proposedLeader = -1;
proposedZxid = -1;
try {
mySocket = new DatagramSocket(port);
// mySocket.setSoTimeout(20000);
} catch (SocketException e1) {
e1.printStackTrace();
throw new RuntimeException();
}
sendqueue = new LinkedBlockingQueue<ToSend>(2 * self.getVotingView().size());
recvqueue = new LinkedBlockingQueue<Notification>(2 * self.getVotingView()
.size());
new Messenger(self.getVotingView().size() * 2, mySocket);
}
示例14: GetPeersTask
import java.net.DatagramSocket; //导入依赖的package包/类
private
GetPeersTask(
DatagramSocket _server,
List<DHTTransportAlternativeContact> _contacts,
byte[] _torrent_hash,
boolean _no_seeds,
LookupListener _listener )
{
server = _server;
torrent_hash = _torrent_hash;
no_seeds = _no_seeds;
listener = _listener;
initial_contacts = _contacts;
tryQuery();
}
示例15: init
import java.net.DatagramSocket; //导入依赖的package包/类
@Override
public void init(DaemonContext context) throws Exception {
System.err.println("Initializing privileged NFS client socket...");
NfsConfiguration conf = new NfsConfiguration();
int clientPort = conf.getInt(NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY,
NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_DEFAULT);
if (clientPort < 1 || clientPort > 1023) {
throw new RuntimeException("Must start privileged NFS server with '" +
NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY + "' configured to a " +
"privileged port.");
}
registrationSocket = new DatagramSocket(
new InetSocketAddress("localhost", clientPort));
registrationSocket.setReuseAddress(true);
args = context.getArguments();
}