当前位置: 首页>>代码示例>>Java>>正文


Java DatagramSocket类代码示例

本文整理汇总了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();
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:28,代码来源:SnmpRequestHandler.java

示例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")));
}
 
开发者ID:Orange-OpenSource,项目名称:OCast-Java,代码行数:21,代码来源:SSDPDiscoveryTest.java

示例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();
    }
}
 
开发者ID:Orange-OpenSource,项目名称:OCast-Java,代码行数:17,代码来源:SSDPDiscoveryTest.java

示例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();
}
 
开发者ID:drytoastman,项目名称:scorekeeperfrontend,代码行数:28,代码来源:Network.java

示例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));
}
 
开发者ID:Orange-OpenSource,项目名称:OCast-Java,代码行数:19,代码来源:SSDPDiscoveryTest.java

示例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;
}
 
开发者ID:Appdome,项目名称:ipack,代码行数:17,代码来源:UDPTransport.java

示例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);
//            }
        }
    }
 
开发者ID:ANDROIDTODO,项目名称:Transmission,代码行数:22,代码来源:BroadcastDiscover.java

示例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);
    }
}
 
开发者ID:AmauryOrtega,项目名称:Sem-Update,代码行数:24,代码来源:VentanaPrincipal.java

示例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 "";
    }
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:22,代码来源:Network.java

示例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);
}
 
开发者ID:mob41,项目名称:broadlink-java-api,代码行数:34,代码来源:BLDevice.java

示例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);
    }
}
 
开发者ID:maoling,项目名称:fuck_zookeeper,代码行数:29,代码来源:LENonTerminateTest.java

示例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();
}
 
开发者ID:ARMmbed,项目名称:java-coap,代码行数:19,代码来源:DatagramSocketTransportTest.java

示例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);
}
 
开发者ID:didichuxing2,项目名称:https-github.com-apache-zookeeper,代码行数:19,代码来源:AuthFastLeaderElection.java

示例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();
}
 
开发者ID:BiglySoftware,项目名称:BiglyBT,代码行数:18,代码来源:DHTTrackerPluginAlt.java

示例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();
}
 
开发者ID:naver,项目名称:hadoop,代码行数:17,代码来源:PrivilegedNfsGatewayStarter.java


注:本文中的java.net.DatagramSocket类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。