@Override public void send(DatagramPacket packet) { SocketAddress socketAddress = packet.getSocketAddress(); if (!peerAddressToChannel.containsKey(socketAddress)) { logger.warn("Peer {} is not bound to a channel", socketAddress); return; } Character channelNumber = peerAddressToChannel.get(socketAddress); byte[] payload = new byte[packet.getLength()]; System.arraycopy( packet.getData(), packet.getOffset(), payload, packet.getOffset(), payload.length); ChannelData channelData = new ChannelData(); channelData.setData(payload); channelData.setChannelNumber(channelNumber); if (logger.isTraceEnabled()) { logger.trace( "Writing {} bytes on channel {}: {}", packet.getLength(), (int) channelNumber, new String(payload, 0, payload.length, StandardCharsets.US_ASCII)); } try { stunStack.sendChannelData(channelData, serverAddress, localAddress); } catch (StunException e) { throw new RuntimeException(e); } }
public void run() { active = true; byte[] b = new byte[PACKET_LENGTH]; DatagramPacket p = new DatagramPacket(b, b.length); while (active) { try { socket.receive(p); // this string constructor which accepts a charset throws an exception if it is // null if (encoding == null) { handlerThread.append(new String(p.getData(), 0, p.getLength())); } else { handlerThread.append(new String(p.getData(), 0, p.getLength(), encoding)); } } catch (SocketException se) { // disconnected } catch (IOException ioe) { ioe.printStackTrace(); } } getLogger().debug("{}'s thread is ending.", MulticastReceiver.this.getName()); }
@Override public void run() { while (true) { try { byte[] dataBuffer = new byte[25600]; // 25kB buffer DatagramPacket packet = new DatagramPacket(dataBuffer, dataBuffer.length); multiplexerSocket.receive(packet); // Check if packet is valid int type = dataBuffer[0] >>> 4; int version = dataBuffer[0] & 0x7; if (version == Packet.VERSION) { try { Packet utpPacket = packetFactory.getFromId(type); Stream inStream = new Stream(packet.getData(), packet.getOffset(), packet.getLength()); utpPacket.read(inStream); UtpSocket socket = new UtpSocket(utpPacket.getConnectionId()); socket = utpSockets.find(socket); if (socket != null) { // log("Received " + utpPacket.getClass().getSimpleName() + " for " + // (utpPacket.getConnectionId() & 0xFFFF)); socket.updateLastInteraction(); utpPacket.process(socket); } else { // log("Packet of " + packet.getLength() + " bytes (0x" + // Integer.toHexString(dataBuffer[0]) + ") was send to a connection which was not // established (" + packet.getAddress() + ":" + packet.getPort() + " | " + // utpPacket.getConnectionId() + ")"); } } catch (IllegalArgumentException e) { log( "Invalid Packet of " + packet.getLength() + " bytes with type " + type + " (" + packet.getAddress() + ":" + packet.getPort() + ")", true); } } else { log( "Invalid Packet of " + packet.getLength() + " bytes with version " + version + " (" + packet.getAddress() + ":" + packet.getPort() + ")", true); } } catch (IOException e) { } } }
public FakeNodeAddress(DatagramPacket packet) { this.clientAddress = packet.getAddress(); int ipxLength = packet.getLength(); byte[] buffer = Arrays.copyOf(packet.getData(), packet.getLength()); this.port = (int) ((buffer[ipxLength - 2] << 8) & 0x0000FF00) | (buffer[ipxLength - 1] & 0x000000FF); }
private static void readData(String command, DatagramSocket clientSocket, String hostName) throws IOException { int hostPort = 69, dataSize = 0; boolean display = false; FileOutputStream myFile = null; long startTime = System.currentTimeMillis(); InetAddress hostAddress = InetAddress.getByName(hostName); ByteArrayOutputStream requestBytes = createPacket(command); byte[] myResponseData = new byte[516]; byte[] myRequestData = new byte[516]; byte[] fileData = new byte[512]; myRequestData = requestBytes.toByteArray(); DatagramPacket myDatagramReceivePacket = new DatagramPacket(myResponseData, myResponseData.length); DatagramPacket myDatagramSendPacket = new DatagramPacket(myRequestData, requestBytes.size(), hostAddress, hostPort); clientSocket.send(myDatagramSendPacket); clientSocket.setSoTimeout(5000); try { do { clientSocket.receive(myDatagramReceivePacket); hostPort = myDatagramReceivePacket.getPort(); byte[] opcode = new byte[2]; byte[] blockNumber = new byte[2]; opcode = Arrays.copyOfRange(myDatagramReceivePacket.getData(), 0, 2); if (opcode[1] == 5) { readError(myDatagramReceivePacket); } else if (opcode[1] == 3) { clientSocket.setSoTimeout(999999999); display = true; blockNumber = Arrays.copyOfRange(myDatagramReceivePacket.getData(), 2, 4); if (myFile == null) myFile = new FileOutputStream(command); fileData = Arrays.copyOfRange( myDatagramReceivePacket.getData(), 4, myDatagramReceivePacket.getLength()); myFile.write(fileData); dataSize += myDatagramReceivePacket.getLength(); ByteArrayOutputStream ackBytes = new ByteArrayOutputStream(); ackBytes.write(0); ackBytes.write(4); ackBytes.write(blockNumber); for (int i = ackBytes.size(); i < 516; i++) { ackBytes.write(0); } DatagramPacket myDatagramAckSendPacket = new DatagramPacket(ackBytes.toByteArray(), ackBytes.size(), hostAddress, hostPort); clientSocket.send(myDatagramAckSendPacket); } } while ((myDatagramReceivePacket.getLength() == 516)); if (myFile != null) myFile.close(); if (display) { long endTime = System.currentTimeMillis() - startTime; System.out.println("Tranferred " + dataSize + " bytes in " + endTime + " milliseconds."); } } catch (SocketTimeoutException s) { System.out.println("Transfer timed out."); } }
public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("192.168.1.16"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = new String("HELLO"); sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); sentence = new String(receivePacket.getData(), 0, receivePacket.getLength()); if (sentence.equals("##100##")) { System.out.println(sentence + ": Waiting for Red."); } while (!sentence.equals("##200##")) { try { receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); sentence = new String(receivePacket.getData(), 0, receivePacket.getLength()); } catch (Exception e) { } } if (sentence.equals("##200##")) { System.out.println(sentence + ": Red and Blue are connected"); } while (true) { receiveData = new byte[1024]; receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); sentence = new String(receivePacket.getData(), 0, receivePacket.getLength()); if (sentence.equals("##300##")) { break; } System.out.println("RED: " + sentence); sentence = inFromUser.readLine(); sendData = sentence.getBytes(); sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); } System.out.println(sentence + ": Disconnected."); clientSocket.close(); }
public void respond(DatagramPacket packet) { byte[] data = new byte[packet.getLength()]; System.arraycopy(packet.getData(), 0, data, 0, packet.getLength()); try { String s = new String(data, "8859_1"); System.out.println(packet.getAddress() + " at port " + packet.getPort() + " says " + s); } catch (java.io.UnsupportedEncodingException ex) { // This shouldn't happen } }
private Candidate getCandidateFromDatagramResponses(List<DatagramPacket> responses) throws ParserConfigurationException, IOException, RetryException { List<Candidate> candidates = new ArrayList<Candidate>(); for (DatagramPacket recv : responses) { String responseXml = new String(recv.getData(), 0, recv.getLength()); Document xml; System.out.println(); String address = printable(recv.getAddress()); try { xml = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(new ByteArrayInputStream(recv.getData(), 0, recv.getLength())); } catch (SAXException e) { System.out.println("Invalid response XML from " + address + ": " + responseXml); continue; } if (!StringUtils.isBlank(options.candidateTag)) { System.out.println(address + options.candidateTag); continue; } String swarm = getChildElementString(xml.getDocumentElement(), "swarm"); if (swarm == null) { System.out.println(address + " doesn't support swarm"); continue; } String url = options.master == null ? getChildElementString(xml.getDocumentElement(), "url") : options.master; if (url == null) { System.out.println( "Jenkins master at '" + address + "' doesn't have a valid Jenkins URL configuration set. Please go to <jenkins url>/configure and set a valid URL."); continue; } candidates.add(new Candidate(url, swarm)); } if (candidates.isEmpty()) { throw new RetryException("No nearby Jenkins supports swarming"); } System.out.println("Found " + candidates.size() + " eligible Jenkins."); return candidates.get(new Random().nextInt(candidates.size())); }
public void run() { while (listen) { try { byte[] buf = new byte[256]; byte[] buf2 = new byte[256]; DatagramPacket packet = new DatagramPacket(buf, buf.length); InetAddress address; socket.receive(packet); String in = new String(packet.getData(), 0, packet.getLength()); address = packet.getAddress(); int port = packet.getPort(); // newClient = findPort(port, address, newClient); String name = findPerson(port, address); // System.out.println(name); if (in.startsWith("1")) { String nama = new String(packet.getData(), 0, packet.getLength()); nama = nama.substring(1); newClient = new Client(packet.getAddress(), packet.getPort(), nama); threads.add(newClient); String wel = "\nWelcome " + newClient.nama + "\n " + "to quit type \"bye\" and to whisper use prefix @name : "; buf = (wel).getBytes(); packet = new DatagramPacket(buf, buf.length, packet.getAddress(), packet.getPort()); socket.send(packet); wel = " enters the room"; buf = (newClient.nama + wel).getBytes(); Broadcast(address, port, buf); } else if (in.startsWith("@")) { // findPort(port, address, newClient); Whisper(newClient, packet.getData()); } else if (in.equals("bye")) { String bye = name + " is leaving"; buf2 = bye.getBytes(); // packet = new DatagramPacket(buf,buf.length,newClient.address, newClient.port); Broadcast(address, port, buf2); } else { byte[] buf3 = new byte[256]; String text = name + "<broadcast> : " + new String(packet.getData(), 0, packet.getLength()); buf3 = text.getBytes(); Broadcast(packet.getAddress(), packet.getPort(), buf3); } } catch (IOException ex) { Logger.getLogger(DatagramServer.class.getName()).log(Level.SEVERE, null, ex); } } socket.close(); }
SNMP_Parser(DatagramPacket dp) { data = new byte[dp.getLength()]; int i; for (i = 0; i < dp.getLength(); i++) { data[i] = dp.getData()[i]; } pointer = 0; data_remaining = data.length; }
public String toString() { int size = 0; String type = "NONE"; String addr = null; if (packet != null && packet.getAddress() != null && packet.getLength() > 0) { type = RobocolParsable.MsgType.fromByte(packet.getData()[0]).name(); size = packet.getLength(); addr = packet.getAddress().getHostAddress(); } return String.format("RobocolDatagram - type:%s, addr:%s, size:%d", type, addr, size); }
public void run() throws IOException { final byte[] buf = new byte[2 * 4096]; final DatagramPacket p = new DatagramPacket(buf, buf.length); while (true) { socket.receive(p); System.out.write(p.getData(), p.getOffset(), p.getLength()); System.out.flush(); if (out != null) { out.write(p.getData(), p.getOffset(), p.getLength()); out.flush(); } } }
/** * Empfangen einer Nachricht ueber UDP * * @return Referenz auf Nachricht, die empfangen wurde * @param timeout Wartezeit in ms * @throws IOException */ public Object receive(int timeout) throws IOException, SocketTimeoutException { // Maximale Wartezeit fuer Receive am Socket einstellen try { log.info("RECEIVE MIT TIMEOUT: " + timeout); socket.setSoTimeout(timeout); // System.out.println("RECEIVE: Maximale Wartezeit: " + // timeout +" ms"); } catch (SocketException e) { log.error("RECEIVE: " + "Fehler beim Einstellen der maximalen Wartezeit"); throw e; } byte[] bytes = new byte[65527]; DatagramPacket packet = new DatagramPacket(bytes, bytes.length); // System.out.println("VOR: Empfangene Datenlaenge: " + packet.getLength()); try { // Blockiert nur, bis Timeout abgelaufen ist socket.receive(packet); log.debug("RECEIVE: Empfangene Datenlaenge: " + packet.getLength()); System.out.println("RECEIVE: Empfangene Datenlaenge: " + packet.getLength()); } catch (IOException e2) { log.error("RECEIVE: " + "Fehler beim Empfangen einer PDU ueber UDP", e2); throw e2; } ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); ObjectInputStream ois = new ObjectInputStream(bais); Object pdu; try { // System.out.println("RECEIVE: " + // "Verfuegbare Bytes Inputstream des UDP-Sockets:" + // ois.available()); pdu = ois.readObject(); remoteAddress = packet.getAddress(); remotePort = packet.getPort(); log.debug("RECEIVE: " + packet.getPort() + "->" + socket.getLocalPort()); } catch (ClassNotFoundException e) { log.error("RECEIVE: " + "ClassNotFoundException:", e); return null; } log.info("RECEIVE MIT TIMEOUT ENDE: " + timeout); return pdu; }
@Override protected void run() throws Exception { while (isRunning()) { // PACKET RECEIVED socket.receive(packet); int length = packet.getLength(); byte[] data = ByteBuffer.allocate(length).put(packet.getData(), 0, length).array(); SocketAddress address = packet.getSocketAddress(); // ALLOCATE CLIENT SWGClient client = (!connections.containsKey(address)) ? clientFactory.create(address) : connections.get(address); data = packagingService.disassemble(data, client.getCrc()); if (data.length == 1) { // TODO: Queue logout packet // TODO: Disconnect client } else if (data.length == 0) { } else { // TODO: Create SWG Message from data } } }
@Override public void run() { try { socket = new DatagramSocket(port); while (!isClosed) { if (socket.isClosed()) return; byte[] buf = new byte[256]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); ByteArrayInputStream bis = new ByteArrayInputStream(buf, 0, packet.getLength()); BufferedReader in = new BufferedReader(new InputStreamReader(bis)); String msg; while ((msg = in.readLine()) != null) { logger.debug("Read from socket: " + msg); content.add(msg.trim()); } in.close(); } } catch (IOException e) { e.printStackTrace(); } }
public static void main(final String... args) throws Throwable { final String remotehost = args[0]; final int remoteport = Integer.parseInt(args[1]); final DatagramSocket socket = new DatagramSocket(); final byte buffer[] = new byte[512]; final InetSocketAddress remote = new InetSocketAddress(remotehost, remoteport); buffer[0] = ENQUIRY; buffer[1] = END_OF_TRANSMISSION; socket.send(new DatagramPacket(buffer, 2, remote)); final DatagramPacket p = new DatagramPacket(buffer, buffer.length); socket.receive(p); if ((p.getLength() == 2) && (buffer[0] == ACKNOWLEDGE) && (buffer[1] == END_OF_TRANSMISSION)) System.out.println("Connection established"); else { System.out.println("Connection failed"); return; } for (; ; ) { int ptr = 0; for (int d; (d = System.in.read()) != '\n'; ) buffer[ptr++] = (byte) d; socket.send(new DatagramPacket(buffer, ptr, remote)); } }
@Override public SctpChannel accept() throws IOException, SctpException, InvalidKeyException, NoSuchAlgorithmException { logger.setLevel(Level.INFO); DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length); SctpPacket packet = null; while (true) { serverSocket.receive(receivePacket); try { packet = new SctpPacket(buffer, 0, receivePacket.getLength()); } catch (SctpException e) { logger.log(Level.WARNING, e.getMessage()); continue; } logger.log(Level.INFO, "receive new packet"); InetSocketAddress address = new InetSocketAddress(receivePacket.getAddress(), receivePacket.getPort()); packet.apply(address, this); Association association = pendingAssociations.get(address); if (association != null && association.getState() == State.ESTABLISHED) { return new SctpChannel(association); } } }
public void run() { while (true) { try { DatagramSocket ClientSoc = new DatagramSocket(ClinetPortNumber); String Command = "GET"; byte Sendbuff[] = new byte[1024]; Sendbuff = Command.getBytes(); InetAddress ServerHost = InetAddress.getLocalHost(); ClientSoc.send(new DatagramPacket(Sendbuff, Sendbuff.length, ServerHost, 5217)); byte Receivebuff[] = new byte[1024]; DatagramPacket dp = new DatagramPacket(Receivebuff, Receivebuff.length); ClientSoc.receive(dp); NewsMsg = new String(dp.getData(), 0, dp.getLength()); System.out.println(NewsMsg); lblNewsHeadline.setText(NewsMsg); Thread.sleep(5000); ClientSoc.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
public boolean sendValues(String valuesString) { try { outData = valuesString.getBytes("UTF-8"); outPacket = new DatagramPacket(outData, outData.length, srvAddr, serverPort); if (DEBUG) Log.d("Czas_klient: ", Long.toString(System.currentTimeMillis())); clientSocket.send(outPacket); clientSocket.receive(inPacket); String response = new String(inPacket.getData(), 0, inPacket.getLength(), "UTF-8"); if (response.equals("RECV_OK")) { if (DEBUG) Log.d(TAG, "SENT: " + valuesString); return true; } else { if (DEBUG) Log.d(TAG, "Unexptected server values confimation!"); return false; } } catch (Exception e) { if (DEBUG) { e.printStackTrace(); Log.d(TAG, "Error sending values to server!"); } return false; } }
public void run() { System.out.println("ExeUDPServer开始监听..." + UDP_PORT); DatagramSocket ds = null; try { ds = new DatagramSocket(UDP_PORT); } catch (BindException e) { System.out.println("UDP端口使用中...请重关闭程序启服务器"); } catch (SocketException e) { e.printStackTrace(); } while (ds != null) { DatagramPacket dp = new DatagramPacket(buf, buf.length); try { ds.receive(dp); // 得到把该数据包发来的端口和Ip int rport = dp.getPort(); InetAddress addr = dp.getAddress(); String recvStr = new String(dp.getData(), 0, dp.getLength()); System.out.println("Server receive:" + recvStr + " from " + addr + " " + rport); // 给客户端回应 String sendStr = "echo of " + recvStr; byte[] sendBuf; sendBuf = sendStr.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, rport); ds.send(sendPacket); } catch (IOException e) { e.printStackTrace(); } } }
/** * * When you receive a datagram that you expect to be a TFTP packet, you use this factory method * to create the proper TFTPPacket object encapsulating the data contained in that datagram. This * method is the only way you can instantiate a TFTPPacket derived class from a datagram. * * <p> * * @param datagram The datagram containing a TFTP packet. * @return The TFTPPacket object corresponding to the datagram. * @exception org.humbird.soa.common.net.tftp.TFTPPacketException If the datagram does not contain * a valid TFTP packet. * */ public static final TFTPPacket newTFTPPacket(DatagramPacket datagram) throws TFTPPacketException { byte[] data; TFTPPacket packet = null; if (datagram.getLength() < MIN_PACKET_SIZE) { throw new TFTPPacketException("Bad packet. Datagram data length is too short."); } data = datagram.getData(); switch (data[1]) { case READ_REQUEST: packet = new TFTPReadRequestPacket(datagram); break; case WRITE_REQUEST: packet = new TFTPWriteRequestPacket(datagram); break; case DATA: packet = new TFTPDataPacket(datagram); break; case ACKNOWLEDGEMENT: packet = new TFTPAckPacket(datagram); break; case ERROR: packet = new TFTPErrorPacket(datagram); break; default: throw new TFTPPacketException("Bad packet. Invalid TFTP operator code."); } return packet; }
public List<EventReply> receive() throws IOException { byte[] buf = new byte[0xff]; DatagramPacket packet = new DatagramPacket(buf, 0, 0xff); m_dgSocket.receive(packet); byte[] data = packet.getData(); // System.out.println("receive data is : "+new String(data,"utf-8")); StringReader reader = new StringReader(new String(data, 0, packet.getLength(), "utf-8")); EventReceipt receipt = null; try { receipt = (EventReceipt) Unmarshaller.unmarshal(EventReceipt.class, reader); } catch (MarshalException e) { e.printStackTrace(); } catch (ValidationException e) { e.printStackTrace(); } InetAddress remoteAddr = packet.getAddress(); int port = packet.getPort(); List<EventReply> replys = new ArrayList<EventReply>(); if (receipt != null) { String[] uuids = receipt.getUuid(); for (String uuid : uuids) { EventReply reply = new EventReply(remoteAddr, port, uuid); replys.add(reply); } } return replys; }
public int synackLink(SynAck synPack) { /* 请求建立连接 */ PacketManager mag = new PacketManager(Values.HEAD, Values.SYN, 0, Values.SYNACKLEN, null, synPack); DatagramPacket sendPacket = new DatagramPacket( mag.getBuf(), mag.getBuf().length, Values.SERV_ADDRESS, Values.SERV_PORT); try { socket.send(sendPacket); Log.d( "johnchain", "Commander send SYN to server bytes = " + sendPacket.getLength() + "|\n" + Utils.stringSynAck(synPack)); } catch (IOException e) { Log.e("johnchain", "Commander send SYN failed, transmition aborted"); return Values.RST_ERROR; } try { socket.setSoTimeout(Values.SOCKET_TIMEOUT * 2); } catch (SocketException e1) { Log.e("johnchain", "Commander set timeout failed"); } MyMessage myMsg = waitReply(Values.SYN_ACK, sendPacket); if (myMsg != null) return Values.RST_OK; else return Values.RST_TIMEOUT; }
public void send(byte[] buf, DatagramPacket dp) throws InterruptedException, IOException { StringBuilder source = new StringBuilder(); source.append(dp.getAddress()); String dataType = type; byte[] trimmedBuf = Arrays.copyOf(buf, dp.getLength()); String rawPRI = new String(trimmedBuf, 1, 4, Charset.forName("UTF-8")); int i = rawPRI.indexOf(">"); if (i <= 3 && i > -1) { String priorityStr = rawPRI.substring(0, i); int priority = 0; int facility = 0; try { priority = Integer.parseInt(priorityStr); facility = (priority >> 3) << 3; facility = facility / 8; dataType = facilityMap.get(facility); } catch (NumberFormatException nfe) { log.warn("Unsupported format detected by SyslogAdaptor:" + Arrays.toString(trimmedBuf)); } } bytesReceived += trimmedBuf.length; Chunk c = new ChunkImpl(dataType, source.toString(), bytesReceived, trimmedBuf, SyslogAdaptor.this); dest.add(c); }
public void run() { boolean running = true; DatagramPacket msg = new DatagramPacket(b, b.length); logReader.debug("Reader running (Multicast=" + (sock instanceof MulticastSocket) + ")."); while (running) { try { sock.receive(msg); if (debugFull) logReader.debug(":run: PtP datagram received. Size = " + msg.getLength()); if ((ignoreSource != null) && (ignoreSource.getPort() == msg.getPort()) && (ignoreSource.getAddress().equals(msg.getAddress()))) { if (debugFull) logReader.debug(":run: Ignored Last received message"); } else receiveFormatSend(msg); } catch (SocketTimeoutException ste) { // ste.printStackTrace(); } catch (IOException e) { System.err.println("[UdpSimpleSession:reader:run] IOException: " + e.getMessage()); } synchronized (this) { if (terminate) running = false; } } }
public void sendConfiguration(Biasgen biasgen) throws HardwareInterfaceException { if (!isOpen()) { throw new HardwareInterfaceException("not open"); } int MAX_COMMAND_LENGTH_BYTES = 256; for (Pot p : getBiasgen().getPotArray().getPots()) { UDP_VPot vp = (UDP_VPot) p; try { String s = vp.getCommandString(); byte[] b = s.getBytes(); // s.getBytes(Charset.forName("US-ASCII")); socket.send(new DatagramPacket(b, b.length, client)); DatagramPacket packet = new DatagramPacket(new byte[MAX_COMMAND_LENGTH_BYTES], MAX_COMMAND_LENGTH_BYTES); socket.receive(packet); ByteArrayInputStream bis; BufferedReader reader = new BufferedReader( new InputStreamReader( (bis = new ByteArrayInputStream(packet.getData(), 0, packet.getLength())))); String line = reader.readLine(); // .toLowerCase(); log.info("response from " + packet.getAddress() + " : " + line); // System.out.println(line); // debug } catch (SocketTimeoutException to) { log.warning("timeout on waiting for command response on datagram control socket"); } catch (Exception ex) { throw new HardwareInterfaceException( "while sending biases to " + client + " caught " + ex.toString()); } } }
public void run() { try { while (running) { byte[] sendClientData = new byte[512]; byte[] sendServerData = new byte[512]; byte[] receiveClientData = new byte[512]; byte[] receiveServerData = new byte[512]; DatagramPacket receiveClientPacket = receivePacket(receiveClientData, receiveSocket); receiveClientPacket.getLength(); // find port used by client int clientPort = receiveClientPacket.getPort(); DatagramSocket hostSocket = new DatagramSocket(); sendServerData = receiveClientPacket.getData(); sendPacket(sendServerData, serverIPAddress, ServerPort, hostSocket); DatagramPacket receiveServerPacket = receivePacket(receiveServerData, hostSocket); if (receiveServerPacket.getData()[0] == 1) { running = false; } sendClientData = receiveServerPacket.getData(); sendPacket(sendClientData, clientIPAddress, clientPort, hostSocket); hostSocket.close(); } receiveSocket.close(); } catch (Exception e) { e.printStackTrace(); } }
/** * Parse a received packet, and notify the main thread if valid. * * @param packet The locally-received DatagramPacket */ private void handleResponsePacket(DatagramPacket packet) { String strPacket = new String(packet.getData(), 0, packet.getLength()); String tokens[] = strPacket.trim().split("\\s+"); if (tokens.length != 3) { Log.w(LOG_TAG, "Malformed response: expected 3 tokens, got " + tokens.length); return; } BroadcastAdvertisement advert; try { String serviceType = tokens[0]; if (!serviceType.equals(DESIRED_SERVICE)) { return; } String serviceName = tokens[1]; int port = Integer.parseInt(tokens[2]); InetAddress addr = packet.getAddress(); Log.v(LOG_TAG, "Broadcast response: " + serviceName + ", " + addr + ", " + port); advert = new BroadcastAdvertisement(serviceName, addr, port); } catch (NumberFormatException e) { return; } Message message = mHandler.obtainMessage(DeviceFinder.BROADCAST_RESPONSE, advert); mHandler.sendMessage(message); }
public static void main(String[] args) throws IOException { /* 接受发过来的数据 */ // 创建upd socket服务对象 DatagramSocket ds = new DatagramSocket(10039); // 创建数据包,用于存储接收到的数据 byte[] bbuf = new byte[1024]; DatagramPacket dp = new DatagramPacket(bbuf, bbuf.length); // 用socket对象的receive方法将接收到的数据存储到数据包中 ds.receive(dp); // 获取ip String ip = dp.getAddress().getHostAddress(); int port = dp.getPort(); // 获取数据内容 byte[] data = dp.getData(); String text = new String(data, 0, dp.getLength()); System.out.println(ip + ":" + port + ":" + text); ds.close(); }
/** Accept incoming events and processes them. */ @Override public void run() { while (isActive()) { if (datagramSocket.isClosed()) { // OK we're done. return; } try { final byte[] buf = new byte[maxBufferSize]; final DatagramPacket packet = new DatagramPacket(buf, buf.length); datagramSocket.receive(packet); final ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData(), packet.getOffset(), packet.getLength()); logEventInput.logEvents(logEventInput.wrapStream(bais), this); } catch (final OptionalDataException e) { if (datagramSocket.isClosed()) { // OK we're done. return; } logger.error("OptionalDataException eof=" + e.eof + " length=" + e.length, e); } catch (final EOFException e) { if (datagramSocket.isClosed()) { // OK we're done. return; } logger.info("EOF encountered"); } catch (final IOException e) { if (datagramSocket.isClosed()) { // OK we're done. return; } logger.error("Exception encountered on accept. Ignoring. Stack Trace :", e); } } }