当前位置: 首页>>代码示例>>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;未经允许,请勿转载。