當前位置: 首頁>>代碼示例>>Java>>正文


Java DatagramSocket.receive方法代碼示例

本文整理匯總了Java中java.net.DatagramSocket.receive方法的典型用法代碼示例。如果您正苦於以下問題:Java DatagramSocket.receive方法的具體用法?Java DatagramSocket.receive怎麽用?Java DatagramSocket.receive使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.net.DatagramSocket的用法示例。


在下文中一共展示了DatagramSocket.receive方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: 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

示例2: 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

示例3: duplicateTest

import java.net.DatagramSocket; //導入方法依賴的package包/類
@Test
public void duplicateTest() throws Exception {
    DatagramSocket datagramSocket = new DatagramSocket();
    datagramSocket.setSoTimeout(3000);

    CoapPacket cpRequest = new CoapPacket(Method.GET, MessageType.Confirmable, "/test/1", null);
    cpRequest.setMessageId(4321);
    DatagramPacket packet = new DatagramPacket(cpRequest.toByteArray(), cpRequest.toByteArray().length, InetAddress.getLocalHost(), SERVER_PORT);
    DatagramPacket recPacket = new DatagramPacket(new byte[1024], 1024);
    DatagramPacket recPacket2 = new DatagramPacket(new byte[1024], 1024);
    datagramSocket.send(packet);
    datagramSocket.receive(recPacket);

    //send duplicate
    Thread.sleep(20);
    datagramSocket.send(packet);
    datagramSocket.receive(recPacket2);
    datagramSocket.close();
    assertArrayEquals(recPacket.getData(), recPacket2.getData());

}
 
開發者ID:ARMmbed,項目名稱:java-coap,代碼行數:22,代碼來源:ClientServerTest.java

示例4: pingHost

import java.net.DatagramSocket; //導入方法依賴的package包/類
@Override
public void pingHost(String address, int port, Consumer<Host> valid, Consumer<IOException> invalid){
    Thread thread = new Thread(() -> {
        try {

            Serialization ser = (Serialization) UCore.getPrivate(client, "serialization");
            DatagramSocket socket = new DatagramSocket();
            ByteBuffer dataBuffer = ByteBuffer.allocate(64);
            ser.write(dataBuffer, new DiscoverHost());

            dataBuffer.flip();
            byte[] data = new byte[dataBuffer.limit()];
            dataBuffer.get(data);
            socket.send(new DatagramPacket(data, data.length, InetAddress.getByName(address), port));

            socket.setSoTimeout(2000);

            addresses.clear();

            DatagramPacket packet = handler.onRequestNewDatagramPacket();

            socket.receive(packet);

            handler.onDiscoveredHost(packet);

            Host host = addresses.values().next();

            if (host != null) {
                Gdx.app.postRunnable(() -> valid.accept(host));
            } else {
                Gdx.app.postRunnable(() -> invalid.accept(new IOException("Outdated server.")));
            }
        } catch (IOException e) {
            Gdx.app.postRunnable(() -> invalid.accept(e));
        }
    });

    thread.setDaemon(true);
    thread.start();
}
 
開發者ID:Anuken,項目名稱:Mindustry,代碼行數:41,代碼來源:KryoClient.java

示例5: scanForRoku

import java.net.DatagramSocket; //導入方法依賴的package包/類
private String scanForRoku(URL url) throws IOException {
	/* create byte arrays to hold our send and response data */
	byte[] sendData = new byte[1024];
	byte[] receiveData = new byte[1024];

	/* our M-SEARCH data as a byte array */
	String MSEARCH = "M-SEARCH * HTTP/1.1\nHost: " + url.getHost() + ":" + url.getPort() + "\nMan: \"ssdp:discover\"\nST: roku:ecp\n"; 
	sendData = MSEARCH.getBytes();

	/* create a packet from our data destined for 239.255.255.250:1900 */
	DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName(url.getHost()), url.getPort());
	
	/* send packet to the socket we're creating */
	DatagramSocket clientSocket = new DatagramSocket();
	clientSocket.send(sendPacket);
	
	/* recieve response and store in our receivePacket */
	DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
	clientSocket.receive(receivePacket);

	/* get the response as a string */
	String response = new String(receivePacket.getData());

	/* close the socket */
	clientSocket.close();

	/* parse the IP from the response */
	/* the response should contain a line like:
		Location:  http://192.168.1.9:8060/
	   and we're only interested in the address -- not the port.
	   So we find the line, then split it at the http:// and the : to get the address.
	*/
	response = response.toLowerCase();
	String address = response.split("location:")[1].split("\n")[0].split("http://")[1].split(":")[0].trim();
	
	/* return the IP */
	return address;
}
 
開發者ID:wseemann,項目名稱:Jaku,代碼行數:39,代碼來源:DiscoveryRequest.java

示例6: discover

import java.net.DatagramSocket; //導入方法依賴的package包/類
/**
 * 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);
}
 
開發者ID:mguntli,項目名稱:sonos-remote-things,代碼行數:41,代碼來源:SSDPClient.java

示例7: discoverOne

import java.net.DatagramSocket; //導入方法依賴的package包/類
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;
}
 
開發者ID:mguntli,項目名稱:sonos-remote-things,代碼行數:31,代碼來源:SSDPClient.java

示例8: pipe

import java.net.DatagramSocket; //導入方法依賴的package包/類
private void pipe(DatagramSocket from, DatagramSocket to, boolean out)
		throws IOException {
	final byte[] data = new byte[datagramSize];
	final DatagramPacket dp = new DatagramPacket(data, data.length);

	while (true) {
		try {
			from.receive(dp);
			lastReadTime = System.currentTimeMillis();

			if (auth.checkRequest(dp, out)) {
				to.send(dp);
			}

		} catch (final UnknownHostException uhe) {
			log.info("Dropping datagram for unknown host");
		} catch (final InterruptedIOException iioe) {
			// log("Interrupted: "+iioe);
			// If we were interrupted by other thread.
			if (iddleTimeout == 0) {
				return;
			}

			// If last datagram was received, long time ago, return.
			final long timeSinceRead = System.currentTimeMillis()
					- lastReadTime;
			if (timeSinceRead >= iddleTimeout - 100) {
				return;
			}
		}
		dp.setLength(data.length);
	}
}
 
開發者ID:PanagiotisDrakatos,項目名稱:T0rlib4Android,代碼行數:34,代碼來源:UDPRelayServer.java

示例9: main

import java.net.DatagramSocket; //導入方法依賴的package包/類
public static void main(String args[]) throws Exception
      {
       UDPSocket udpsocket = new UDPSocket();
          DatagramSocket serverSocket = new DatagramSocket(80); // Port Nimber
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];
            while(true)
               {
                  DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                  serverSocket.receive(receivePacket);
                  String sentence = new String( receivePacket.getData());
                  System.out.println("RECEIVED: " + sentence);
                  String[] tempdata = sentence.split(",");
                  String module = tempdata[0];
                  String[] temprature = tempdata[1].split(":");
                  System.out.println("Module : "+module);
                   // System.out.println("Temprature : "+temprature[1]);

               //   udpsocket.insertData(receivePacket.getAddress()+"",module,""+temprature[1]);
                  InetAddress IPAddress = receivePacket.getAddress();
                  int port = receivePacket.getPort();
                  String capitalizedSentence = sentence.toUpperCase();
                  sendData = capitalizedSentence.getBytes();
                  System.out.println("IPAddress: " + IPAddress +"  Port : "+port+" Module : "+module);
//                  DatagramPacket sendPacket =
//                  new DatagramPacket(sendData, sendData.length, IPAddress, port);
//                  serverSocket.send(sendPacket);
               }
      }
 
開發者ID:Sanjoth,項目名稱:IOT-AmbientTemperature,代碼行數:30,代碼來源:UDPSocket.java

示例10: sendPkt

import java.net.DatagramSocket; //導入方法依賴的package包/類
/**
 * Sends a compiled packet to a destination host and port, and receives a
 * datagram from the source port specified.
 * 
 * @param sock
 *            Uses an external socket
 * @param pkt
 *            The compiled packet to be sent
 * @param sourceIpAddr
 *            Source IP address to be binded for receiving datagrams
 * @param sourcePort
 *            Source Port to be bineded for receiving datagrams
 * @param destIpAddr
 *            Destination IP address
 * @param destPort
 *            Destination Port
 * @param timeout
 *            Socket timeout. 0 will disable the timeout
 * @param bufSize
 *            Receiving datagram's buffer size
 * @return The received datagram
 * @throws IOException
 *             Thrown if socket timed out, cannot bind source IP and source
 *             port, no permission, etc.
 */
public static DatagramPacket sendPkt(DatagramSocket sock, Packet pkt, InetAddress sourceIpAddr, int sourcePort,
        InetAddress destIpAddr, int destPort, int timeout, int bufSize) throws IOException {
    // sock.bind(new InetSocketAddress(ipAddr, sourcePort));

    byte[] data = pkt.getData();
    log.debug("DESTIP: " + destIpAddr.getHostAddress());
    log.debug("DESTPORT: " + destPort);
    DatagramPacket sendpack = new DatagramPacket(data, data.length, destIpAddr, destPort);
    sock.send(sendpack);

    byte[] rece = new byte[bufSize];
    DatagramPacket recepack = new DatagramPacket(rece, 0, rece.length);

    long startTime = System.currentTimeMillis();
    long elapsed;
    while ((elapsed = System.currentTimeMillis() - startTime) < timeout) {
        try {
            sock.send(sendpack);
            sock.setSoTimeout(1000);
            sock.receive(recepack);
            break;
        } catch (SocketTimeoutException e) {
            if (elapsed > timeout) {
                break;
            }

            continue;
        }
    }

    return recepack;
}
 
開發者ID:mob41,項目名稱:broadlink-java-api,代碼行數:58,代碼來源:BLDevice.java

示例11: run

import java.net.DatagramSocket; //導入方法依賴的package包/類
public void run() throws IOException {
  InetAddress IPAddress = InetAddress.getByName(host);
  byte[] sendData = request.getBytes();
  byte[] receiveData = new byte[65535];
  // Use the provided socket if there is one, else just make a new one.
  DatagramSocket socket = this.clientSocket == null ?
      new DatagramSocket() : this.clientSocket;

  try {
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
        IPAddress, port);
    socket.send(sendPacket);
    socket.setSoTimeout(500);
    DatagramPacket receivePacket = new DatagramPacket(receiveData,
        receiveData.length);
    socket.receive(receivePacket);

    // Check reply status
    XDR xdr = new XDR(Arrays.copyOfRange(receiveData, 0,
        receivePacket.getLength()));
    RpcReply reply = RpcReply.read(xdr);
    if (reply.getState() != RpcReply.ReplyState.MSG_ACCEPTED) {
      throw new IOException("Request failed: " + reply.getState());
    }
  } finally {
    // If the client socket was passed in to this UDP client, it's on the
    // caller of this UDP client to close that socket.
    if (this.clientSocket == null) {
      socket.close();
    }
  }
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:33,代碼來源:SimpleUdpClient.java

示例12: getAccessibleNetworkAddressAtMediator

import java.net.DatagramSocket; //導入方法依賴的package包/類
public String getAccessibleNetworkAddressAtMediator(String networkName, Mediator mediator) {

        // TODO: Remove as soon as mediation is working..
        if (true) {
            return "0:0";
        }

        try {
            DatagramSocket clientSocket = new DatagramSocket();
            byte[] sendData = ("JOIN:" + networkName).getBytes("UTF-8");
            DatagramPacket sendPacket = new DatagramPacket(sendData,
                    sendData.length, InetAddress.getByName(mediator.getUrl()), Constants.MEDIATION_SERVER_PORT);
            clientSocket.send(sendPacket);

            DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);
            clientSocket.receive(receivePacket);
            String response = new String(receivePacket.getData());
            response = NetworkUtilities.getCleanString(response);
            System.out.println("Response: " + response);
            if(response.equals("ERROR"))
                return null;
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
開發者ID:Hatzen,項目名稱:EasyPeasyVPN,代碼行數:28,代碼來源:MediationConnector.java

示例13: main

import java.net.DatagramSocket; //導入方法依賴的package包/類
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);
    }
}
 
開發者ID:spacetimeme,項目名稱:DreamSocket,代碼行數:10,代碼來源:UDPServer.java

示例14: main

import java.net.DatagramSocket; //導入方法依賴的package包/類
public static void main(String[] args) throws IOException{
	char[] msg = new char[4];
	packetLength = (maxClusters*8)+4+4;
	xPos = new float[maxClusters];
	yPos = new float[maxClusters];
	xHistogram = new short[dsx];
	maxHistogramX = 1;
	byte[] buf = new byte[packetLength];

	DatagramSocket socket = new DatagramSocket(commandPort);

	System.out.println("Einstein Tunnel Display Method");

	while(true){
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		socket.receive(packet);
		//seq #
		int packetNumber = ((buf[0] & 0xFF) << 24)
			| ((buf[1] & 0xFF) << 16)
			| ((buf[2] & 0xFF) << 8)
			| (buf[3] & 0xFF);
		//msg
		msg[0]=(char)(buf[4]);
		msg[1]=(char)(buf[5]);
		msg[2]=(char)(buf[6]);
		msg[3]=(char)(buf[7]);
		//nrc
		nrClusters = (((buf[8] & 0xFF) << 8)
			| (buf[9] & 0xFF));
		//data
		if((msg[0]=='h') && (msg[1]=='i') && (msg[2]=='s')){
			readHistogramPacket(buf);
			packetCount++;
		}
		if((msg[0]=='p') && (msg[1]=='o') && (msg[2]=='s')){
			readPositionPacket(buf);
			//System.out.println("Read position... first position: "+xPos[0]);
			packetCount++;
		}
		checkInput();
		displayCanvas.repaint();
		if (packetNumber>packetCount){
			System.out.println("Lost Packet! "+packetNumber);
			packetCount = packetNumber;
		}
	}
}
 
開發者ID:SensorsINI,項目名稱:jaer,代碼行數:48,代碼來源:EinsteinTunnelDisplay.java

示例15: downloadData

import java.net.DatagramSocket; //導入方法依賴的package包/類
private void downloadData() throws SocketException, UnknownHostException, IOException, InterruptedException{
  DatagramSocket clientSocket = new DatagramSocket();
  System.out.println("Starting remote desktop session with "+ip);
  InetAddress IPAddress = InetAddress.getByName(ip);
      byte[] sendData;
      byte[] receiveData = new byte[16384];
      
      String sentence = "hndshk";
      
      sendData = sentence.getBytes();
      
      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7998);
      clientSocket.send(sendPacket);
      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
      
      clientSocket.receive(receivePacket);
      System.out.println("Received.");
      String modifiedSentence = "error";
      
      modifiedSentence = processData(receivePacket.getData());
      
      String first = modifiedSentence.split("_")[0];
      
      if(modifiedSentence.contains("_")){
          String second = modifiedSentence.split("_")[1];
          if(!second.isEmpty()){
            if(!second.contains("\n")){
               System.out.println("TEXT FROM SERVER: "+second.trim());
            }else{
                System.out.println("TEXT FROM SERVER: ENTER");
            }
               
          }else{
              System.out.println("EMPTY");
          }
      }
      
      double xloc = Double.parseDouble(first.split(":")[0]);
      double yloc = Double.parseDouble(first.split(":")[1]);
      if(x != xloc && y != yloc){
        System.out.println("FROM SERVER:" +x+" "+y * screenDim.height);
        x = xloc * screenDim.width;
        y = yloc * screenDim.height;
      }
      executeOperations();
      System.out.println("Data downloaded.");
      Thread.sleep(1000);
  
}
 
開發者ID:Obsidiam,項目名稱:ameliaclient,代碼行數:50,代碼來源:RemoteDesktopThread.java


注:本文中的java.net.DatagramSocket.receive方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。