java.net.DatagramPacket Java Examples

The following examples show how to use java.net.DatagramPacket. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MilightBinding.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
protected void sendMessage(String messageBytes, String bridgeId) {

        String bridgeIp = bridgeIpConfig.get(bridgeId);
        Integer bridgePort = bridgePortConfig.get(bridgeId);

        if (bridgePort == null) {
            bridgePort = DEFAULT_PORT;
        }

        try {
            byte[] buffer = getMessageBytes(messageBytes);

            InetAddress IPAddress = InetAddress.getByName(bridgeIp);
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, IPAddress, bridgePort);
            DatagramSocket datagramSocket = new DatagramSocket();
            datagramSocket.send(packet);
            datagramSocket.close();
            logger.debug("Sent packet '{}' to bridge '{}' ({}:{})",
                    new Object[] { messageBytes, bridgeId, bridgeIp, bridgePort });
        } catch (Exception e) {
            logger.error("Failed to send Message to '{}': ", new Object[] { bridgeIp, e.getMessage() });
        }
    }
 
Example #2
Source File: SimpleSyslogServer.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void run(){

    while (!closed.get()){
        try {
            DatagramPacket packet = new DatagramPacket(new byte[2048], 2048);
            socket.receive(packet);
            byte[] bytes = new byte[packet.getLength()];
            System.arraycopy(packet.getData(), 0, bytes, 0, packet.getLength());
            receivedData.add(bytes);
        } catch (IOException e) {
            if (!closed.get()){
                e.printStackTrace();
                close();
            }
        }
    }
}
 
Example #3
Source File: UDPSlaveTerminal.java    From jamod with Apache License 2.0 6 votes vote down vote up
public void run() {
	do {
		try {
			// 1. Prepare buffer and receive package
			byte[] buffer = new byte[256];// max size
			DatagramPacket packet = new DatagramPacket(buffer,
					buffer.length);
			m_Socket.receive(packet);
			// 2. Extract TID and remember request
			Integer tid = new Integer(ModbusUtil.registersToInt(buffer));
			m_Requests.put(tid, packet);
			// 3. place the data buffer in the queue
			m_ReceiveQueue.put(buffer);
			if (Modbus.debug)
				System.out.println("Received package to queue.");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	} while (m_Continue);
}
 
Example #4
Source File: SnmpRequestHandler.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #5
Source File: MulticastDiscoveryAgent.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    final byte[] buf = new byte[BUFF_SIZE];
    final DatagramPacket packet = new DatagramPacket(buf, 0, buf.length);
    while (running.get()) {
        tracker.checkServices();
        try {
            multicast.receive(packet);
            if (packet.getLength() > 0) {
                final String str = new String(packet.getData(), packet.getOffset(), packet.getLength());
                //                        System.out.println("read = " + str);
                tracker.processData(str);
            }
        } catch (SocketTimeoutException se) {
            // ignore
        } catch (IOException e) {
            if (running.get()) {
                LOGGER.error("failed to process packet: " + e);
            }
        }
    }
}
 
Example #6
Source File: Client.java    From jblink with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
    Sends a collection of messages to the server

    @param objs the messages to send
    @throws BlinkException if there is a schema or binding problem
    @throws IOException if there is a socket or communications problem
 */

 public void send (Iterable<?> objs) throws BlinkException, IOException
 {
    wr.write (objs);
    wr.flush ();

    if (udpsock != null)
    {
byte [] data = bs.toByteArray ();
bs.reset ();
DatagramPacket p =
   new DatagramPacket (data, data.length,
		udpsock.getRemoteSocketAddress ());
udpsock.send (p);
    }
 }
 
Example #7
Source File: DatagramLogger.java    From oodt with Apache License 2.0 6 votes vote down vote up
public static void main(String[] argv) throws Throwable {
	if (argv.length > 0) {
		System.err.println("This program takes NO command line arguments.");
		System.err.println("Set the activity.port property to adjust the port number.");
		System.err.println("Set the activity.storage property to set the Storage class to use.");
		System.exit(1);
	}
	int port = Integer.getInteger("activity.port", VAL);
	String className = System.getProperty("activity.storage");
	if (className == null) {
		System.err.println("No Storage class defined via the `activity.storage' property; exiting...");
		System.exit(1);
	}
	Class storageClass = Class.forName(className);
	storage = (Storage) storageClass.newInstance();
	DatagramSocket socket = new DatagramSocket(port);
	byte[] buf = new byte[INT];
	DatagramPacket packet = new DatagramPacket(buf, buf.length);
	for (;;) {
		socket.receive(packet);
		byte[] received = new byte[packet.getLength()];
		System.arraycopy(packet.getData(), packet.getOffset(), received, 0, packet.getLength());
		new ReceiverThread(received).start();
	} 
}
 
Example #8
Source File: DatagramSocketAdaptor.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public void receive(DatagramPacket p) throws IOException {
    synchronized (dc.blockingLock()) {
        if (!dc.isBlocking())
            throw new IllegalBlockingModeException();
        try {
            synchronized (p) {
                ByteBuffer bb = ByteBuffer.wrap(p.getData(),
                                                p.getOffset(),
                                                p.getLength());
                SocketAddress sender = receive(bb);
                p.setSocketAddress(sender);
                p.setLength(bb.position() - p.getOffset());
            }
        } catch (IOException x) {
            Net.translateException(x);
        }
    }
}
 
Example #9
Source File: DNSServer.java    From personaldnsfilter with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void resolve(DatagramPacket request, DatagramPacket response) throws IOException {
    for (int i = 0; i<2; i++) { //retry once in case of EOFException (pooled connection was already closed)
        Connection con = Connection.connect(address, timeout, ssl, null, Proxy.NO_PROXY);
        con.setSoTimeout(timeout);
        try {
            DataInputStream in = new DataInputStream(con.getInputStream());
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeShort(request.getLength());
            out.write(request.getData(), request.getOffset(), request.getLength());
            out.flush();
            int size = in.readShort();
            readResponseFromStream(in, size, response);
            response.setSocketAddress(address);
            con.release(true);
            return;
        } catch (EOFException eof) {
            con.release(false);
            if (i == 1)
                throw new IOException ("EOF when reading from "+this.toString(),eof); // retried already once, now throw exception
        } catch (IOException eio) {
            con.release(false);
            throw eio;
        }
    }
}
 
Example #10
Source File: LANServerRegistration.java    From seventh with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 
 */
public LANServerRegistration(final ServerContext serverContext) {
    
    final LANServerConfig config = serverContext.getConfig().getLANServerConfig();
    this.listener = new BroadcastListener(config.getMtu(), config.getBroadcastAddress(), config.getPort());
    this.listener.addOnMessageReceivedListener(new OnMessageReceivedListener() {
            
        @Override
        public void onMessage(DatagramPacket packet) {
            String msg = new String(packet.getData(), packet.getOffset(), packet.getLength()).trim();
            if(msg.equalsIgnoreCase("ping")) {
                try(Broadcaster caster = new Broadcaster(config.getMtu(), config.getBroadcastAddress(), config.getPort())) {
                    ServerInfo info = new ServerInfo(serverContext);
                    caster.broadcastMessage(info.toString());
                }
                catch(Exception e) {
                    Cons.println("*** ERROR: Unable to broadcast response: " + e);
                }
            }
        }
    });
    
}
 
Example #11
Source File: SSDPPacketTest.java    From Connect-SDK-Android-Core with Apache License 2.0 6 votes vote down vote up
@Test
public void testParseLowercaseDatagram() {
    String testDatagramData =
            "NOTIFY * HTTP/1.1\r\n" +
            "host: 239.255.255.250:1900\r\n" +
            "nt: nt_value\r\n" +
            "Nts: ssdp:byebye\r\n" +
            "uSN: uuid:advertisement_UUID\r\n\r\n";
    mDatagramPacket = new DatagramPacket(testDatagramData.getBytes(), 0);
    ssdpPacket = new SSDPPacket(mDatagramPacket);
    Assert.assertEquals("NOTIFY * HTTP/1.1", ssdpPacket.getType());
    Assert.assertEquals("239.255.255.250:1900", ssdpPacket.getData().get("HOST"));
    Assert.assertEquals("nt_value", ssdpPacket.getData().get("NT"));
    Assert.assertEquals("ssdp:byebye", ssdpPacket.getData().get("NTS"));
    Assert.assertEquals("uuid:advertisement_UUID", ssdpPacket.getData().get("USN"));
}
 
Example #12
Source File: Socks5DatagramPacketHandler.java    From sockslib with Apache License 2.0 6 votes vote down vote up
@Override
public DatagramPacket encapsulate(DatagramPacket packet, SocketAddress destination) throws
    SocksException {
  if (destination instanceof InetSocketAddress) {
    InetSocketAddress destinationAddress = (InetSocketAddress) destination;
    final byte[] data = packet.getData();
    final InetAddress remoteServerAddress = packet.getAddress();
    final byte[] addressBytes = remoteServerAddress.getAddress();
    final int ADDRESS_LENGTH = remoteServerAddress.getAddress().length;
    final int remoteServerPort = packet.getPort();
    byte[] buffer = new byte[6 + packet.getLength() + ADDRESS_LENGTH];

    buffer[0] = buffer[1] = 0; // reserved byte
    buffer[2] = 0; // fragment byte
    buffer[3] = (byte) (ADDRESS_LENGTH == 4 ? AddressType.IPV4 : AddressType.IPV6);
    System.arraycopy(addressBytes, 0, buffer, 4, ADDRESS_LENGTH);
    buffer[4 + ADDRESS_LENGTH] = SocksUtil.getFirstByteFromInt(remoteServerPort);
    buffer[5 + ADDRESS_LENGTH] = SocksUtil.getSecondByteFromInt(remoteServerPort);
    System.arraycopy(data, 0, buffer, 6 + ADDRESS_LENGTH, packet.getLength());
    return new DatagramPacket(buffer, buffer.length, destinationAddress.getAddress(),
        destinationAddress.getPort());
  } else {
    throw new IllegalArgumentException("Only support java.net.InetSocketAddress");
  }
}
 
Example #13
Source File: SnmpAdaptorServer.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Send the specified message on trapSocket.
 */
private void sendTrapMessage(SnmpMessage msg)
    throws IOException, SnmpTooBigException {

    byte[] buffer = new byte[bufferSize] ;
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length) ;
    int encodingLength = msg.encodeMessage(buffer) ;
    packet.setLength(encodingLength) ;
    packet.setAddress(msg.address) ;
    packet.setPort(msg.port) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sending trap to " + msg.address + ":" +
              msg.port);
    }
    trapSocket.send(packet) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sent to " + msg.address + ":" +
              msg.port);
    }
    snmpOutTraps++;
    snmpOutPkts++;
}
 
Example #14
Source File: WirelessHidService.java    From WirelessHid with Apache License 2.0 6 votes vote down vote up
private void sendDisconnectMsg() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            if (mMulticastSocket != null) {
                DatagramPacket packet = new DatagramPacket(Constant.HID_SERVICE_DISCONNECT.getBytes(),
                        Constant.HID_SERVICE_DISCONNECT.length(),
                        group, Constant.HID_MULTICAST_PORT);
                try {
                    mMulticastSocket.send(packet);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                mPCDiscoverer.stopDiscover();
            }
        }
    }).start();
}
 
Example #15
Source File: UdpMaster.java    From modbus4j with GNU General Public License v3.0 6 votes vote down vote up
private IpMessageResponse receiveImpl() throws IOException, ModbusTransportException {
    DatagramPacket packet = new DatagramPacket(new byte[MESSAGE_LENGTH], MESSAGE_LENGTH);
    socket.receive(packet);

    // We could verify that the packet was received from the same address to which the request was sent,
    // but let's not bother with that yet.

    ByteQueue queue = new ByteQueue(packet.getData(), 0, packet.getLength());
    IpMessageResponse response;
    try {
        response = (IpMessageResponse) messageParser.parseMessage(queue);
    }
    catch (Exception e) {
        throw new ModbusTransportException(e);
    }

    if (response == null)
        throw new ModbusTransportException("Invalid response received");

    return response;
}
 
Example #16
Source File: DiscoveryThread.java    From LocalNetwork with MIT License 6 votes vote down vote up
@Override
public void run() {
    try {
        int port = NetworkUtil.BASE_PORT;
        do {
            socket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0"));
            port--;
        } while (socket == null);

        socket.setBroadcast(true);

        while (true) {
            // Receive broadcast packet
            byte[] buffer = new byte[15000];
            DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
            socket.receive(receivePacket);
            Log.d("USER", "Received packet from: " + receivePacket.getAddress().getHostAddress());

            // Send reply
            byte[] replyPacket = SerializationUtil.serialize(reply);
            socket.send(new DatagramPacket(replyPacket, replyPacket.length, receivePacket.getAddress(), receivePacket.getPort()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #17
Source File: SnmpAdaptorServer.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Send the specified message on trapSocket.
 */
private void sendTrapMessage(SnmpMessage msg)
    throws IOException, SnmpTooBigException {

    byte[] buffer = new byte[bufferSize] ;
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length) ;
    int encodingLength = msg.encodeMessage(buffer) ;
    packet.setLength(encodingLength) ;
    packet.setAddress(msg.address) ;
    packet.setPort(msg.port) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sending trap to " + msg.address + ":" +
              msg.port);
    }
    trapSocket.send(packet) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sent to " + msg.address + ":" +
              msg.port);
    }
    snmpOutTraps++;
    snmpOutPkts++;
}
 
Example #18
Source File: UDPRelayServer.java    From sockslib with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  try {
    byte[] buffer = new byte[bufferSize];
    while (running) {
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
      server.receive(packet);
      if (isFromClient(packet)) {
        datagramPacketHandler.decapsulate(packet);
        server.send(packet);
      } else {
        packet =
            datagramPacketHandler.encapsulate(packet, new InetSocketAddress(clientAddress,
                clientPort));
        server.send(packet);
      }
    }
  } catch (IOException e) {
    if (e.getMessage().equalsIgnoreCase("Socket closed") && !running) {
      logger.debug("UDP relay server stopped");
    } else {
      logger.error(e.getMessage(), e);
    }
  }
}
 
Example #19
Source File: UDPSlaveTerminal.java    From jamod with Apache License 2.0 6 votes vote down vote up
public void run() {
	do {
		try {
			// 1. pickup the message and corresponding request
			byte[] message = (byte[]) m_SendQueue.take();
			DatagramPacket req = (DatagramPacket) m_Requests
					.remove(new Integer(ModbusUtil
							.registersToInt(message)));
			// 2. create new Package with corresponding address and port
			DatagramPacket res = new DatagramPacket(message,
					message.length, req.getAddress(), req.getPort());
			m_Socket.send(res);
			if (Modbus.debug)
				System.out.println("Sent package from queue.");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	} while (m_Continue || !m_SendQueue.isEmpty());
}
 
Example #20
Source File: SimpleUdpClient.java    From big-c with Apache License 2.0 5 votes vote down vote up
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();
    }
  }
}
 
Example #21
Source File: WirelessHidServer.java    From WirelessHid with Apache License 2.0 5 votes vote down vote up
private static Thread getDisconnectListenThread() {
	return new Thread(new Runnable() {
		
		@Override
		public void run() {
			while (true) {
				DatagramPacket packet = new DatagramPacket(new byte[256], 256);
				try {
					multicastSocket.receive(packet);
					
					if (packet.getAddress().equals(mCurrentAndroid) && mSocket != null) {
					
						String msg = new String(packet.getData()).trim();
						
						if (Constant.HID_SERVICE_DISCONNECT.equals(msg)) {
							is.close();
							System.out.println("##########################DISCONNECTED###########################");
							System.out.println("receive disconnect msg, so disconnect it.");
							break;
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
					try {
						is.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
					break;
				}
			}
			
			System.out.println("disconnect message listen thread exit.");
		}
	});
}
 
Example #22
Source File: LightwaveRfBindingFunctionalTest.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private Answer<DatagramPacket> sendMessageOnceUnlatched(final String data, final CyclicBarrier latch) {
    return new Answer<DatagramPacket>() {
        @Override
        public DatagramPacket answer(InvocationOnMock invocation)
                throws InterruptedException, BrokenBarrierException {
            Object[] args = invocation.getArguments();
            ((DatagramPacket) args[0]).setData(data.getBytes());
            latch.await();
            latch.reset();
            return null;
        }
    };
}
 
Example #23
Source File: BroadcastBrowsingProvider.java    From samba-documents-provider with GNU General Public License v3.0 5 votes vote down vote up
private void sendNameQueryBroadcast(
        DatagramSocket socket,
        InetAddress address) throws IOException {
  byte[] data = BroadcastUtils.createPacket(mTransId);
  int dataLength = data.length;

  DatagramPacket packet = new DatagramPacket(data, 0, dataLength, address, NBT_PORT);
  socket.send(packet);

  if (BuildConfig.DEBUG) Log.d(TAG, "Broadcast package sent");
}
 
Example #24
Source File: StunServer.java    From freeacs with MIT License 5 votes vote down vote up
private void setDatagramAddress(ResponseAddress ra, DatagramPacket receive, DatagramPacket send)
    throws UtilityException, UnknownHostException {
  if (ra != null) {
    send.setPort(ra.getPort());
    send.setAddress(ra.getAddress().getInetAddress());
  } else {
    send.setPort(receive.getPort());
    send.setAddress(receive.getAddress());
  }
}
 
Example #25
Source File: UDPServer.java    From javase with MIT License 5 votes vote down vote up
public static void main(String[] args) {
		//DatagramSocket socket = null;
		byte[] bufRecv = null; byte[] bufResp = null;
		
		// re-factored with "try with resources"
		//try {
			//socket = new DatagramSocket(7778);
		try (DatagramSocket socket = new DatagramSocket(7778)) {
			System.out.println("UDP Server bind on 7778 port.");
			while (true) {
				bufRecv = new byte[256];
				
				// receive request
				DatagramPacket packet = 
						new DatagramPacket(bufRecv, bufRecv.length);
				socket.receive(packet);
				
				//bufRecv = packet.getData();
				System.out.println("Client says: " + new String(bufRecv));
				
				// figure out the response
				String respString = new String("OK");
				bufResp = respString.getBytes();
				
				// send the response at the client address and port
				InetAddress address = packet.getAddress();
				int port = packet.getPort();
				DatagramPacket packetResp = 
						new DatagramPacket(bufResp, bufResp.length, address, port);
				socket.send(packetResp);
				
			} // end while
		} catch(IOException ioe) {
			ioe.printStackTrace();
		} 
//		finally {
//			if (socket != null) 
//				socket.close();
//		}
	}
 
Example #26
Source File: Offset.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {

        byte b1[] = new byte[1024];
        DatagramPacket p = new DatagramPacket(b1, 512, 512 );

        byte b2[] = new byte[20];
        p.setData(b2);

        if (p.getOffset() != 0) {
            throw new Exception("setData(byte[]) didn't reset offset");
        }
    }
 
Example #27
Source File: Response.java    From hola with MIT License 5 votes vote down vote up
private Response(DatagramPacket packet) {
    this();
    byte[] dstBuffer = buffer.array();
    System.arraycopy(packet.getData(), packet.getOffset(), dstBuffer, 0, packet.getLength());
    buffer.limit(packet.getLength());
    buffer.position(0);
}
 
Example #28
Source File: MulticastGroup.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private void send(String msg) throws RemotingException {
    DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), mutilcastAddress, mutilcastSocket.getLocalPort());
    try {
        mutilcastSocket.send(hi);
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example #29
Source File: Offset.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {

        byte b1[] = new byte[1024];
        DatagramPacket p = new DatagramPacket(b1, 512, 512 );

        byte b2[] = new byte[20];
        p.setData(b2);

        if (p.getOffset() != 0) {
            throw new Exception("setData(byte[]) didn't reset offset");
        }
    }
 
Example #30
Source File: Socks5UDPAssociateClient.java    From sockslib with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {

    DatagramSocket clientSocket = null;
    Socks5 proxy = new Socks5(new InetSocketAddress("localhost", 1080));

    try {
      NetworkMonitor networkMonitor = new NetworkMonitor();
      clientSocket = new Socks5DatagramSocket(proxy);
      clientSocket = new MonitorDatagramSocketWrapper(clientSocket, networkMonitor);
      String message = "I am client using SOCKS proxy";
      byte[] sendBuffer = message.getBytes();
      DatagramPacket packet =
          new DatagramPacket(sendBuffer, sendBuffer.length, new InetSocketAddress("localhost",
              5050));
      clientSocket.send(packet);


      //Received response message from UDP server.
      byte[] receiveBuf = new byte[100];
      DatagramPacket receivedPacket = new DatagramPacket(receiveBuf, receiveBuf.length);
      clientSocket.receive(receivedPacket);
      String receiveStr = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
      System.out.println("received:" + receiveStr);

      System.out.println("UDP client information:");
      System.out.println("Total Sent:     " + networkMonitor.getTotalSend() + " bytes");
      System.out.println("Total Received: " + networkMonitor.getTotalReceive() + " bytes");
      System.out.println("Total:          " + networkMonitor.getTotal() + " bytes");

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      ResourceUtil.close(clientSocket);
    }

  }