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


Java DatagramSocket.send方法代碼示例

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


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

示例1: 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:l294265421,項目名稱:ZooKeeper,代碼行數:29,代碼來源:LENonTerminateTest.java

示例2: detectMac_udp

import java.net.DatagramSocket; //導入方法依賴的package包/類
private void detectMac_udp(){
	for(int i=0;i<10;i++){
		try {
			DatagramSocket ds=new DatagramSocket();
			DatagramPacket dp=new DatagramPacket(new byte[1000], 1000);
			dp.setAddress(InetAddress.getByName(testIp_udp));
			dp.setPort(5555);
			ds.send(dp);
			ds.close();
			Thread.sleep(500);
			if(local_mac!=null){
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				Thread.sleep(1);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}

}
 
開發者ID:jonasxiao,項目名稱:FinalSpeed,代碼行數:25,代碼來源:CapEnv.java

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

示例4: send

import java.net.DatagramSocket; //導入方法依賴的package包/類
public IOException send(byte[] data){
	try {
		DatagramSocket socket = null;
		if(Server.isHosting()) socket = Server.getSocket();
		else if(Client.isConnected()) socket = Client.getSocket();
		 
		String d = new String(data, 0, data.length).trim();

		data = d.getBytes();
		if(socket != null){
			socket.send(new DatagramPacket(data, data.length, InetAddress.getByName(ip), port));
			return null;
		}else{
			return new IOException("SClient error. Could not get the current socket.");
		}
	} catch (IOException e) {
		return e;
	}
}
 
開發者ID:giannismarinakis,項目名稱:java-open-nl,代碼行數:20,代碼來源:SClient.java

示例5: sendMessage

import java.net.DatagramSocket; //導入方法依賴的package包/類
public IOException sendMessage(String data){
	try {
		DatagramSocket socket = null;
		if(Server.isHosting()) socket = Server.getSocket();
		else if(Client.isConnected()) socket = Client.getSocket();
		 
		int myID = (Server.isHosting()) ? -1 : Client.getID();
		String d;
		byte[] finalData;
		d = "m#"+myID+"#" + data; 
		finalData = d.getBytes();
		if(socket != null){
			socket.send(new DatagramPacket(finalData, finalData.length, InetAddress.getByName(ip), port));
			return null;
		}else{
			return new IOException("SClient error. Could not get the current socket.");
		}
	} catch (IOException e) {
		return e;
	}
}
 
開發者ID:giannismarinakis,項目名稱:java-open-nl,代碼行數:22,代碼來源:SClient.java

示例6: run

import java.net.DatagramSocket; //導入方法依賴的package包/類
public void run() 
{
   try // deliver message
   {         
      // create DatagramSocket for sending message
      DatagramSocket socket = 
         new DatagramSocket( MULTICAST_SENDING_PORT );
      
      // use InetAddress reserved for multicast group
      InetAddress group = InetAddress.getByName( MULTICAST_ADDRESS );
      
      // create DatagramPacket containing message
      DatagramPacket packet = new DatagramPacket( messageBytes, 
         messageBytes.length, group, MULTICAST_LISTENING_PORT );
      
      socket.send( packet ); // send packet to multicast group
      socket.close(); // close socket
   } // end try
   catch ( IOException ioException ) 
   { 
      ioException.printStackTrace();
   } // end catch
}
 
開發者ID:cleitonferreira,項目名稱:LivroJavaComoProgramar10Edicao,代碼行數:24,代碼來源:MulticastSender.java

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

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

示例9: sendBroadcast

import java.net.DatagramSocket; //導入方法依賴的package包/類
private void sendBroadcast(DatagramSocket datagramSocket) {


        try {
            InetAddress inetAddress = InetAddress.getByName(Packet.getInstance().getCurrentBroadcastIpName());
            ByteArrayOutputStream byteArrayOutputStream = getOutputStream();
//            TLog.e("send port :"+ datagramSocket.getPort());
            DatagramPacket datagramPacket = new DatagramPacket(byteArrayOutputStream.toByteArray(), byteArrayOutputStream.toByteArray().length, inetAddress, T.BROADCAST_UDP_PORT);
            datagramSocket.send(datagramPacket);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
開發者ID:ANDROIDTODO,項目名稱:Transmission,代碼行數:15,代碼來源:BroadcastSend.java

示例10: sendRPC

import java.net.DatagramSocket; //導入方法依賴的package包/類
@SuppressWarnings("resource")
private static void sendRPC(RPCMode mode, int groupID, Sender sender, SClient client, String methodName, Object... arguments) {
	DatagramSocket socket;
	String args = "";
	//Converts the passed arguments to String
	for (Object object : arguments) {
		//Get the code of the argument (String -> 1, Integer -> 2, etc...)
		int typecode = getTypeCode(object.getClass());
		String str = object.toString(); 
		args += str.length() + "." + typecode + str; 
	}
	//Get the current ID, -1 for Server.
	int id = Client.isConnected() ? Client.getID() : -1;

	//The final data for the RPC
	String data = "";
	
	if(sender == null && client == null) {
		data = "rpc"+id+"#" + mode + "#"+groupID+"@" + methodName + "@" + arguments.length + "@" + args;
	}else {
		int i_d;
		
		if(sender != null)
			i_d = sender.isServer ? -1 : sender.getClient().getID();
		else 
			i_d = client.getID();
		
		data = "rpc"+id+"#id." + i_d + "#"+groupID+"@" + methodName + "@" + arguments.length + "@" + args;
	}
	
	byte[] bdata = data.getBytes();
	
	socket = Server.isHosting() ? Server.getSocket() : Client.getSocket();
	try {
		socket.send(new DatagramPacket(bdata, bdata.length, Server.isHosting() ? InetAddress.getByName("localhost") : InetAddress.getByName(Client.getServerIP()), Server.isHosting() ? Server.getPort() : Client.getServerPort()));
	} catch (IOException e) { 
		e.printStackTrace();
	} 		
}
 
開發者ID:giannismarinakis,項目名稱:java-open-nl,代碼行數:40,代碼來源:RPC.java

示例11: testRegistration

import java.net.DatagramSocket; //導入方法依賴的package包/類
@Test(timeout = 1000)
public void testRegistration() throws IOException, InterruptedException {
  XDR req = new XDR();
  RpcCall.getInstance(++xid, RpcProgramPortmap.PROGRAM,
      RpcProgramPortmap.VERSION,
      RpcProgramPortmap.PMAPPROC_SET,
      new CredentialsNone(), new VerifierNone()).write(req);

  PortmapMapping sent = new PortmapMapping(90000, 1,
      PortmapMapping.TRANSPORT_TCP, 1234);
  sent.serialize(req);

  byte[] reqBuf = req.getBytes();
  DatagramSocket s = new DatagramSocket();
  DatagramPacket p = new DatagramPacket(reqBuf, reqBuf.length,
      pm.getUdpServerLoAddress());
  try {
    s.send(p);
  } finally {
    s.close();
  }

  // Give the server a chance to process the request
  Thread.sleep(100);
  boolean found = false;
  @SuppressWarnings("unchecked")
  Map<String, PortmapMapping> map = (Map<String, PortmapMapping>) Whitebox
      .getInternalState(pm.getHandler(), "map");

  for (PortmapMapping m : map.values()) {
    if (m.getPort() == sent.getPort()
        && PortmapMapping.key(m).equals(PortmapMapping.key(sent))) {
      found = true;
      break;
    }
  }
  Assert.assertTrue("Registration failed", found);
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:39,代碼來源:TestPortmap.java

示例12: sendString

import java.net.DatagramSocket; //導入方法依賴的package包/類
private void sendString(String s) throws SocketException, UnknownHostException, IOException{
	outputSocket = new DatagramSocket(sendPort);
	outputSocket.setSoTimeout(100);
	byte[] b = s.getBytes();
	InetAddress IPAddress =  InetAddress.getByName(powerSupplyIP);
	powerSupplySocketAddress = new InetSocketAddress(IPAddress,sendPort);
	DatagramPacket d = new DatagramPacket(b,b.length,powerSupplySocketAddress);
	if (outputSocket != null){
	    outputSocket.send(d);
	    outputSocket.close();
	}
}
 
開發者ID:SensorsINI,項目名稱:jaer,代碼行數:13,代碼來源:Resetter.java

示例13: activateCameras

import java.net.DatagramSocket; //導入方法依賴的package包/類
private void activateCameras() {
    try{
        controlPort = CONTROL_PORT;
        localhost = "localhost";
        outputSocket = new DatagramSocket(CONNECT_PORT);
        outputSocket.setSoTimeout(100);
    } catch ( IOException ex ){
        log.warning(ex.toString());
    }
    log.info("sending activation commands to cameras");
    for(int i=cameraDomainOffset; i<=(cameraDomainOffset+MAX_NUM_CAMERAS); i++){
        String s = "t+\r\n";
        byte[] b = s.getBytes();
        try{
            InetAddress IPAddress =  InetAddress.getByName(cameraDomain+i);
            cameraSocketAddress = new InetSocketAddress(IPAddress,controlPort);
            log.info("send "+b+" to "+IPAddress.getHostAddress()+":"+controlPort);
            DatagramPacket d = new DatagramPacket(b,b.length,cameraSocketAddress);
            if (outputSocket != null){
	//repeat the sending 10 to be sure of data transmission
	for(int j=0; j<10; j++){
		outputSocket.send(d);
	}
            }
        } catch ( Exception e ){
            log.warning(e.toString());
        }
    }
}
 
開發者ID:SensorsINI,項目名稱:jaer,代碼行數:30,代碼來源:MultiUDPNetworkDVS128Camera.java

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

示例15: datagramSocket

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

    socket.setTrafficClass(0x10);
    socket.send(new DatagramPacket(DATA, 3, InetAddress.getByName(DESTINATION), 5683));
    System.out.println("VERIFY IN WIRESHARK THAT PACKET'S TRAFFIC-CLASS IS SET!");

    assertEquals(0x10, socket.getTrafficClass());
    socket.close();
}
 
開發者ID:ARMmbed,項目名稱:java-coap,代碼行數:12,代碼來源:TrafficClassVerifier.java


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