public void run() { final byte[] receive_buf = new byte[65535]; DatagramPacket packet = new DatagramPacket(receive_buf, receive_buf.length); byte[] data; ByteArrayInputStream inp_stream; DataInputStream inp = null; Message msg; while (mcast_sock != null && receiver != null && Thread.currentThread().equals(receiver)) { packet.setData(receive_buf, 0, receive_buf.length); try { mcast_sock.receive(packet); data = packet.getData(); inp_stream = new ExposedByteArrayInputStream(data, 0, data.length); inp = new DataInputStream(inp_stream); msg = new Message(); msg.readFrom(inp); up(new Event(Event.MSG, msg)); } catch (SocketException socketEx) { break; } catch (Throwable ex) { log.error("failed receiving packet (from " + packet.getSocketAddress() + ")", ex); } finally { Util.close(inp); } } if (log.isTraceEnabled()) log.trace("receiver thread terminated"); }
private String lookupFarm() { if (Response != null) { if (Response.isStillValid()) { return Response.getFarmID(); } Response = null; } try { InetAddress CDPServer; DatagramSocket Socket; CDPQuery Query; byte[] Buffer; DatagramPacket Packet; /* Get the IP address of the CDP servers. */ CDPServer = InetAddress.getByName(CDPServerName); /* Create a UDP socket for the CDP query. */ Socket = new DatagramSocket(); Socket.setSoTimeout(CDPTimeout); /* Build the CDP query. */ Query = new CDPQuery(Constants.AZUREUS_NAME + " " + Constants.AZUREUS_VERSION); Buffer = Query.getBytes(); Packet = new DatagramPacket(Buffer, Buffer.length, CDPServer, CDPPort); /* Send the query to the CDP server. */ Socket.send(Packet); /* Receive the CDP response. */ Buffer = new byte[CDPResponse.MaxSize]; Packet.setData(Buffer); Socket.receive(Packet); if (Packet.getAddress() != CDPServer || Packet.getPort() != CDPPort) throw (new Exception("CDP server address mismatch on response")); /* Parse the CDP response. */ Response = new CDPResponse(Packet.getData()); /* Return the farmID from the CDP response. */ return Response.getFarmID(); } catch (Throwable Excpt) { if (Excpt instanceof UnknownHostException) { } else { Excpt.printStackTrace(); } return "default"; } }
public static void main(final String[] args) throws Exception { // System.setProperty("java.net.preferIPv4Stack", "true"); if (2 != args.length && 3 != args.length) { System.out.println( "Usage: java MulticastSender <multicast address> <number of messages> [interface]"); return; } final String address = args[0]; final long count = Long.parseLong(args[1]); final int port = 4445; final int serverPort = 4447; final byte[] buffer = "This is a test string with sufficient data to send".getBytes("ASCII"); final InetAddress group = InetAddress.getByName(address); MulticastSocket socket; if (3 == args.length) { final String interfaceAddress = args[2]; System.out.println("Binding to interface: " + interfaceAddress); socket = new MulticastSocket(new InetSocketAddress(interfaceAddress, serverPort)); } else { socket = new MulticastSocket(serverPort); } final DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port); final MulticastSender sender = new MulticastSender(); final Thread t = new Thread(sender); t.setDaemon(true); t.start(); for (long i = count; --i != 0; ) { packet.setData(buffer); socket.send(packet); sender.messageCounter++; } Thread.sleep(1000); socket.close(); }
public void runClient() throws IOException { try { dataClient = new DatagramSocket(); dataOut = "1".getBytes(); dataSent = new DatagramPacket(dataOut, dataOut.length, getAddress(), getPort()); dataClient.send(dataSent); Scanner input = new Scanner(System.in); // setSocket(new Socket(getAddress(),getPort())); // in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // out = new PrintWriter(socket.getOutputStream(),true); while (true) { /* Preparing Input from Server */ // serverResponse = in.readLine(); try { dataReceived.setData(dataIn); dataClient.receive(dataReceived); serverResponse = new String(dataReceived.getData()); if (serverResponse.equals("1")) { // if key for getting client input is called /* Outputting to Server */ clientResponse = input.nextLine(); // Get what the user types. dataOut = clientResponse.getBytes(); dataSent = new DatagramPacket(dataOut, dataOut.length, getAddress(), getPort()); dataClient.send(dataSent); // out.println(clientResponse); } else { System.out.println(serverResponse); } } catch (Exception e) { } } } catch (Exception e) { /**/ } finally { /* socket.close(); */ } }
/** Method to keep the connection alive with the name server */ public void run() { boolean connected = false; int ticket = 0; int serial = -1; int time = 1000; DatagramPacket inPack = new DatagramPacket(new byte[1024], 1024); DatagramPacket outPack = new DatagramPacket(new byte[1024], 1024); ByteArrayOutputStream outBuf = new ByteArrayOutputStream(); DataInputStream inData; DataOutputStream outData = new DataOutputStream(outBuf); while (running) { if (!connected) { // Thoust ought Register thine self try { outBuf.reset(); outData.writeByte(0); outData.writeUTF(userName); outData.writeInt(portNum); outData.flush(); outPack.setData(outBuf.toByteArray()); nameServer.send(outPack); } catch (IOException e) { System.err.println("LeetActive: " + e); } } else { // Thoust ought Renew thine self try { outBuf.reset(); outData.writeByte(2); outData.writeInt(ticket); outData.flush(); outPack.setData(outBuf.toByteArray()); nameServer.send(outPack); } catch (IOException e) { System.err.println(e); } } // Now we will receive a packet... try { nameServer.receive(inPack); inData = new DataInputStream(new ByteArrayInputStream(inPack.getData())); byte type = inData.readByte(); if (type == 1) { // Twas a ticket packet try { ticket = inData.readInt(); if (ticket > -1) { // Make sure its not evil connected = true; } else { connected = false; } time = inData.readInt(); } catch (IOException e) { System.err.println(e); } } if (type == 5) { // Twas an update packet try { int s = inData.readInt(); if (s > serial) { // Make sure its not old serial = s; int size = inData.readInt(); ArrayList newList = new ArrayList(size); for (int x = 0; x < size; x++) { newList.add( new String( "" + inData.readUTF() + "@" + inData.readUTF() + ":" + inData.readInt())); } if (!newList.equals(hostList)) { hostList = newList; updated = true; } } } catch (IOException e) { System.err.println(e); } } } catch (SocketTimeoutException e) { // Server hates you connected = false; System.err.println(e); } catch (IOException e) { System.err.println(e); } try { // Take a nap sleep(time / 4); } catch (InterruptedException e) { } } }
public void run() { DatagramPacket packet; byte receive_buf[] = new byte[65535]; int len; byte[] tmp, data; // moved out of loop to avoid excessive object creations (bela March 8 2001) packet = new DatagramPacket(receive_buf, receive_buf.length); while (mcast_receiver != null && mcast_sock != null) { try { packet.setData(receive_buf, 0, receive_buf.length); mcast_sock.receive(packet); len = packet.getLength(); data = packet.getData(); if (len == 1 && data[0] == 0) { if (Trace.debug) { Trace.info("UDP.run()", "received dummy packet"); } continue; } if (len == 4) { // received a diagnostics probe if (data[0] == 'd' && data[1] == 'i' && data[2] == 'a' && data[3] == 'g') { handleDiagnosticProbe(packet.getAddress(), packet.getPort()); continue; } } if (Trace.debug) { Trace.info( "UDP.receive()", "received (mcast) " + packet.getLength() + " bytes from " + packet.getAddress() + ":" + packet.getPort() + " (size=" + len + " bytes)"); } if (len > receive_buf.length) { Trace.error( "UDP.run()", "size of the received packet (" + len + ") is bigger than " + "allocated buffer (" + receive_buf.length + "): will not be able to handle packet. " + "Use the FRAG protocol and make its frag_size lower than " + receive_buf.length); } if (Version.compareTo(data) == false) { Trace.warn( "UDP.run()", "packet from " + packet.getAddress() + ":" + packet.getPort() + " has different version (" + Version.printVersionId(data, Version.version_id.length) + ") from ours (" + Version.printVersionId(Version.version_id) + "). This may cause problems"); } if (use_incoming_packet_handler) { tmp = new byte[len]; System.arraycopy(data, 0, tmp, 0, len); incoming_queue.add(tmp); } else { handleIncomingUdpPacket(data); } } catch (SocketException sock_ex) { if (Trace.trace) { Trace.info("UDP.run()", "multicast socket is closed, exception=" + sock_ex); } break; } catch (InterruptedIOException io_ex) { // thread was interrupted ; // go back to top of loop, where we will terminate loop } catch (Throwable ex) { Trace.error("UDP.run()", "exception=" + ex + ", stack trace=" + Util.printStackTrace(ex)); Util.sleep(300); // so we don't get into 100% cpu spinning (should NEVER happen !) } } if (Trace.trace) { Trace.info("UDP.run()", "multicast thread terminated"); } }
@Override public void run() { try { // Create a packet for sending data DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length); OutputStream outputStream = null; String fileName = ""; boolean createFile = true; int bytesReceived = 0; long totalBytesReceived = 0; long fileSize = 0; socket.receive(receivePacket); // Display the client number textArea.append("Starting thread for UDP client " + clientNo + " at " + new Date() + '\n'); textArea.append( "The client host name is " + receivePacket.getAddress().getHostName() + " and port number is " + receivePacket.getPort() + '\n'); // Continuously serve the client while (true) { bytesReceived = receivePacket.getLength(); if (bytesReceived > 0) { // Get the file transmission header from the initial client packet String transmitHeader = new String(receivePacket.getData(), 0, bytesReceived); // transmitHeader = transmitHeader.substring(0, bytesReceived).trim().; String[] header = transmitHeader.split(HEADER_DEL); fileSize = Long.parseLong(header[0]); fileName = header[1]; // Send receipt acknowledgment back to the client. Just send back the number of bytes // received. setSendPacketAddress(sendPacket, receivePacket); sendPacket.setData(String.valueOf(bytesReceived).getBytes()); socket.send(sendPacket); } while (totalBytesReceived < fileSize) { // Wait for client to send bytes // socket.setSendBufferSize(BUFFER_SIZE); socket.receive(receivePacket); bytesReceived = receivePacket.getLength(); if (totalBytesReceived == 0) { if (createFile) { // Get a unique name for the file to be received // fileName = getUniqueFileName(); fileName = textFolder.getText() + fileName; outputStream = createFile(fileName); createFile = false; textArea.append("Receiving file from client.\n"); } // Write bytes to file outputStream.write(receivePacket.getData(), 0, bytesReceived); } else { if (outputStream != null) { // Write bytes to file, if any outputStream.write(receivePacket.getData(), 0, bytesReceived); } } // Increment total bytes received totalBytesReceived += bytesReceived; // Tell the client to send more data. Just send back the number of bytes received. sendPacket.setData(String.valueOf(bytesReceived).getBytes()); socket.send(sendPacket); // buffer = new byte[BUFFER_SIZE]; Arrays.fill(buffer, (byte) 0); receivePacket = new DatagramPacket(buffer, buffer.length); } outputStream.flush(); outputStream.close(); textArea.append("Received file successfully. Saved as " + fileName + "\n"); // Tell the client transmission is complete. Just send back the total number of bytes // received. sendPacket.setData(String.valueOf(totalBytesReceived).getBytes()); socket.send(sendPacket); // Reset creation flag createFile = true; totalBytesReceived = 0; // Wait for client to send another file socket.receive(receivePacket); } } catch (IOException e) { System.err.println(e); } }
/** The listening thread's run method. */ @Override public void run() { DatagramPacket packet = null; while (this.running) { try { IceSocketWrapper localSock; synchronized (sockLock) { if (!running) return; localSock = this.sock; } /* * Make sure localSock's receiveBufferSize is taken into * account including after it gets changed. */ int receiveBufferSize = 1500; /* if(localSock.getTCPSocket() != null) { receiveBufferSize = localSock.getTCPSocket(). getReceiveBufferSize(); } else if(localSock.getUDPSocket() != null) { receiveBufferSize = localSock.getUDPSocket(). getReceiveBufferSize(); } */ if (packet == null) { packet = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize); } else { byte[] packetData = packet.getData(); if ((packetData == null) || (packetData.length < receiveBufferSize)) { packet.setData(new byte[receiveBufferSize], 0, receiveBufferSize); } else { /* * XXX Tell the packet it is large enough because the * socket will not look at the length of the data array * property and will just respect the length property. */ packet.setLength(receiveBufferSize); } } localSock.receive(packet); // get lost if we are no longer running. if (!running) return; logger.finest("received datagram"); RawMessage rawMessage = new RawMessage( packet.getData(), packet.getLength(), new TransportAddress( packet.getAddress(), packet.getPort(), listenAddress.getTransport()), listenAddress); messageQueue.add(rawMessage); } catch (SocketException ex) { if (running) { logger.log( Level.WARNING, "Connector died: " + listenAddress + " -> " + remoteAddress, ex); stop(); // Something wrong has happened errorHandler.handleFatalError( this, "A socket exception was thrown" + " while trying to receive a message.", ex); } else { // The exception was most probably caused by calling // this.stop(). } } catch (ClosedChannelException cce) { logger.log(Level.WARNING, "A net access point has gone useless:", cce); stop(); errorHandler.handleFatalError( this, "ClosedChannelException occurred while listening" + " for messages!", cce); } catch (IOException ex) { logger.log(Level.WARNING, "A net access point has gone useless:", ex); errorHandler.handleError(ex.getMessage(), ex); // do not stop the thread; } catch (Throwable ex) { logger.log(Level.WARNING, "A net access point has gone useless:", ex); stop(); errorHandler.handleFatalError( this, "Unknown error occurred while listening for messages!", ex); } } }