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