List of usage examples for java.net DatagramSocket DatagramSocket
public DatagramSocket() throws SocketException
From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java
@Test public void testAsMapFalse() throws Exception { SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean( SyslogReceivingChannelAdapterFactoryBean.Protocol.udp); int port = SocketUtils.findAvailableUdpSocket(1514); factory.setPort(port);/*from ww w .ja va 2 s .c o m*/ PollableChannel outputChannel = new QueueChannel(); factory.setOutputChannel(outputChannel); factory.setBeanFactory(mock(BeanFactory.class)); factory.afterPropertiesSet(); factory.start(); UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject(); DefaultMessageConverter defaultMessageConverter = new DefaultMessageConverter(); defaultMessageConverter.setAsMap(false); adapter.setConverter(defaultMessageConverter); Thread.sleep(1000); byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes("UTF-8"); DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port)); DatagramSocket socket = new DatagramSocket(); socket.send(packet); socket.close(); Message<?> message = outputChannel.receive(10000); assertNotNull(message); assertEquals("WEBERN", message.getHeaders().get("syslog_HOST")); assertEquals("<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE", new String((byte[]) message.getPayload(), "UTF-8")); adapter.stop(); }
From source file:org.mule.test.firewall.FirewallTestCase.java
protected DatagramSocket openUdpClient() throws IOException { try {// w ww .j a v a2s . com return new DatagramSocket(); } catch (IOException e) { logger.error("Could not open UDP client"); throw e; } }
From source file:org.loggo.server.SimpleServerIT.java
@Test(timeout = 60 * 1000) public void sunnyDay() throws Exception { // no log files exist assertEquals(0, Iterators.size(conn.createScanner("logs", Authorizations.EMPTY).iterator())); // send a tcp message Socket s = new Socket("localhost", loggerPort); assertTrue(s.isConnected());/* www. j a v a 2 s. c o m*/ s.getOutputStream() .write("localhost tester 2014-01-01 01:01:01,123 This is a test message\n\n".getBytes(UTF_8)); s.close(); // send a udp message DatagramSocket ds = new DatagramSocket(); String otherMessage = "localhost test2 2014-01-01 01:01:01,345 [INFO] This is a 2nd message"; byte[] otherMessageBytes = otherMessage.getBytes(UTF_8); InetSocketAddress dest = new InetSocketAddress("localhost", loggerPort); ds.send(new DatagramPacket(otherMessageBytes, otherMessageBytes.length, dest)); ds.close(); // wait for a flush sleepUninterruptibly(8, TimeUnit.SECONDS); // verify the messages are stored Scanner scanner = conn.createScanner("logs", Authorizations.EMPTY); assertEquals(2, Iterators.size(scanner.iterator())); Iterator<Entry<Key, Value>> iter = scanner.iterator(); Entry<Key, Value> next = iter.next(); assertEquals(next.getValue().toString(), "This is a test message"); assertEquals(next.getKey().getColumnQualifier().toString(), "tester\0localhost"); assertEquals(next.getKey().getColumnFamily().toString(), "UNKNOWN"); assertTrue(next.getKey().getRow().toString().endsWith("2014-01-01 01:01:01,123")); next = iter.next(); assertEquals(next.getValue().toString(), "[INFO] This is a 2nd message"); assertEquals(next.getKey().getColumnQualifier().toString(), "test2\0localhost"); assertTrue(next.getKey().getRow().toString().endsWith("2014-01-01 01:01:01,123")); assertFalse(iter.hasNext()); sleepUninterruptibly(30, TimeUnit.SECONDS); conn.tableOperations().deleteRows("logs", null, null); }
From source file:com.example.nate.cloudcar.MainActivity.java
public void socketSend(final String chan, final int pos) { new Thread(new Runnable() { public void run() { try { int msgLength = chan.length(); DatagramSocket s = new DatagramSocket(); InetAddress local = InetAddress.getByName("192.168.10.200"); byte[] message = chan.getBytes(); DatagramPacket chanPacket = new DatagramPacket(message, msgLength, local, server_port); s.send(chanPacket);/*from w w w . j av a 2s.co m*/ msgLength = Integer.toString(pos).length(); message = Integer.toString(pos).getBytes(); DatagramPacket posPacket = new DatagramPacket(message, msgLength, local, server_port); s.send(posPacket); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); Thread.currentThread().interrupted(); }
From source file:snapshotTools.java
private String callOvnmanager(String node, String action) { String result = ""; DatagramSocket socket = null; int serverPort = 9999; DatagramPacket packet2Send;//from w ww.j a v a2s .c om DatagramPacket receivedPacket; InetAddress theServerAddress; byte[] outBuffer; byte[] inBuffer; inBuffer = new byte[8192]; outBuffer = new byte[8192]; try { HttpSession session = RuntimeAccess.getInstance().getSession(); String sessionUser = (String) session.getAttribute("User"); if (sessionUser == null) { sessionUser = "administrator"; } JSONObject joCmd = new JSONObject(); JSONObject joAction = new JSONObject(action); joCmd.put("sender", sessionUser); joCmd.put("target", "SNAPSHOT"); joCmd.put("node", node); joCmd.put("action", joAction); String output = joCmd.toString(); socket = new DatagramSocket(); String actionName = joAction.get("name").toString(); if (actionName.equals("create")) { socket.setSoTimeout(180000); } else { socket.setSoTimeout(60000); } InetAddress serverInet = InetAddress.getByName("localhost"); socket.connect(serverInet, serverPort); outBuffer = output.getBytes(); packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort); try { // send the data socket.send(packet2Send); receivedPacket = new DatagramPacket(inBuffer, inBuffer.length); socket.receive(receivedPacket); // the server response is... result = new String(receivedPacket.getData(), 0, receivedPacket.getLength()); session.setAttribute("LastActive", System.currentTimeMillis()); } catch (Exception excep) { String msg = excep.getMessage(); //String msg = excep.toString(); joCmd.remove("action"); joAction.put("result", "Error:" + msg); joCmd.put("action", joAction); result = joCmd.toString(); } socket.close(); } catch (Exception e) { log(ERROR, "callOvnmanager", e); return e.toString(); } return result; }
From source file:com.vivareal.logger.appender.UDPAppender.java
void connect(InetAddress address, int port) { if (this.address == null) { return;// w w w. j a v a2 s . c om } try { // First, close the previous connection if any. cleanUp(); outSocket = new DatagramSocket(); outSocket.connect(address, port); } catch (IOException e) { LogLog.error("Could not open UDP Socket for sending. We will try again later.", e); fireConnector(); } }
From source file:sx.blah.discord.api.internal.UDPVoiceSocket.java
/** * Called when the voice gateway receives {@link VoiceOps#READY}. This performs IP discovery and sends * {@link VoiceOps#SELECT_PROTOCOL} on the voice gateway. * * @param endpoint The endpoint to send audio data to. * @param port The port to send audio data on. * @param ssrc The self user's ssrc.//from w w w . j a v a 2 s . c om */ synchronized void setup(String endpoint, int port, int ssrc) { try { this.udpSocket = new DatagramSocket(); this.address = new InetSocketAddress(endpoint, port); this.ssrc = ssrc; Pair<String, Integer> ourIp = doIPDiscovery(ssrc); udpSocket.setSoTimeout(5); //after IP discovery, every usage times out after 5ms, because it's better to drop a frame than block the thread. SelectProtocolRequest selectRequest = new SelectProtocolRequest(ourIp.getLeft(), ourIp.getRight()); voiceWS.send(VoiceOps.SELECT_PROTOCOL, selectRequest); } catch (IOException e) { Discord4J.LOGGER.error(LogMarkers.VOICE_WEBSOCKET, "Encountered error opening voice UDP socket: ", e); } }
From source file:com.barchart.udt.AppServer.java
private static InetAddress getLocalHostViaUdp() throws UnknownHostException { final InetSocketAddress sa = new InetSocketAddress("www.google.com", 80); DatagramSocket sock = null;/*from w ww .j av a 2s. c o m*/ try { sock = new DatagramSocket(); sock.connect(sa); final InetAddress address = sock.getLocalAddress(); return address; } catch (final SocketException e) { log.warn("Exception getting address", e); return InetAddress.getLocalHost(); } finally { if (sock != null) { sock.close(); } } }
From source file:QuoteServerThread.java
public void init() { //Initialize networking stuff. String host = getCodeBase().getHost(); try {//from w ww .ja va 2 s . c o m address = InetAddress.getByName(host); } catch (UnknownHostException e) { System.out.println("Couldn't get Internet address: Unknown host"); // What should we do? } try { socket = new DatagramSocket(); } catch (IOException e) { System.out.println("Couldn't create new DatagramSocket"); return; } //Set up the UI. GridBagLayout gridBag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setLayout(gridBag); Label l1 = new Label("Quote of the Moment:", Label.CENTER); c.anchor = GridBagConstraints.SOUTH; c.gridwidth = GridBagConstraints.REMAINDER; gridBag.setConstraints(l1, c); add(l1); display = new Label("(no quote received yet)", Label.CENTER); c.anchor = GridBagConstraints.NORTH; c.weightx = 1.0; c.fill = GridBagConstraints.HORIZONTAL; gridBag.setConstraints(display, c); add(display); Label l2 = new Label("Enter the port (on host " + host + ") to send the request to:", Label.RIGHT); c.anchor = GridBagConstraints.SOUTH; c.gridwidth = 1; c.weightx = 0.0; c.weighty = 1.0; c.fill = GridBagConstraints.NONE; gridBag.setConstraints(l2, c); add(l2); portField = new TextField(6); gridBag.setConstraints(portField, c); add(portField); Button button = new Button("Send"); gridBag.setConstraints(button, c); add(button); portField.addActionListener(this); button.addActionListener(this); }
From source file:com.carreygroup.JARVIS.Demon.java
/******************************TCP * @throws UnknownHostException ******************************/ public boolean Connection(byte mode, String argv1, String argv2) throws UnknownHostException { Ethnet_Mode = mode;/* ww w.java2 s .co m*/ if (Ethnet_Mode == Ethnet.P2P) { P2PConnect(argv1, argv2); } else if (Ethnet_Mode == Ethnet.TCP) { //,IP java.net.InetAddress x; x = java.net.InetAddress.getByName(argv1); String host = x.getHostAddress();//ip int port = Integer.valueOf(argv2); try { mSocket = new Socket(); mAddress = new InetSocketAddress(host, port); mSocket.connect(mAddress, 5000); mPrintWriterClient = new PrintWriter(mSocket.getOutputStream(), true); if (mSocket.isConnected()) Log.v("_DEBUG", "Connected!"); else Log.v("_DEBUG", "No Connected!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // // new Thread(new ActiveTest(mSocket.socket())).start(); } else if (Ethnet_Mode == Ethnet.UDP) { //,IP java.net.InetAddress x; x = java.net.InetAddress.getByName(argv1); String host = x.getHostAddress();//ip int port = Integer.valueOf(argv2); mAddress = new InetSocketAddress(host, port); try { mSendPSocket = new DatagramSocket(); mSendPSocket.setBroadcast(true); mReceviedSocket = new DatagramSocket(port); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } if (Connected()) { for (ConnectionListener listener : mConnListeners) { listener.onConnected(this); } } return Connected(); }