public void run() { if (ServerSocket == null) return; while (true) { try { InetAddress address; int port; DatagramPacket packet; byte[] data = new byte[1460]; packet = new DatagramPacket(data, data.length); ServerSocket.receive(packet); // // address = packet.getAddress(); port = packet.getPort(); System.out.println("get the Client port is: " + port); System.out.println("get the data length is: " + data.length); FileWriter fw = new FileWriter("Fortunes.txt"); PrintWriter out = new PrintWriter(fw); for (int i = 0; i < data.length; i++) { out.print(data[i] + " "); } out.close(); System.out.println("Data has been writen to destination!"); packet = new DatagramPacket(data, data.length, address, port); ServerSocket.send(packet); System.out.println("Respond has been made!"); } catch (Exception e) { System.err.println("Exception: " + e); e.printStackTrace(); } } }
@Scheduled(fixedDelay = Integer.MAX_VALUE) public void startListening() { if (disable) { return; } log.info("Starting UPNP Discovery Listener"); try (DatagramSocket responseSocket = new DatagramSocket(upnpResponsePort); MulticastSocket upnpMulticastSocket = new MulticastSocket(UPNP_DISCOVERY_PORT); ) { InetSocketAddress socketAddress = new InetSocketAddress(UPNP_MULTICAST_ADDRESS, UPNP_DISCOVERY_PORT); Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces(); while (ifs.hasMoreElements()) { NetworkInterface xface = ifs.nextElement(); Enumeration<InetAddress> addrs = xface.getInetAddresses(); String name = xface.getName(); int IPsPerNic = 0; while (addrs.hasMoreElements()) { InetAddress addr = addrs.nextElement(); log.debug(name + " ... has addr " + addr); if (InetAddressUtils.isIPv4Address(addr.getHostAddress())) { IPsPerNic++; } } log.debug("Checking " + name + " to our interface set"); if (IPsPerNic > 0) { upnpMulticastSocket.joinGroup(socketAddress, xface); log.debug("Adding " + name + " to our interface set"); } } while (true) { // trigger shutdown here byte[] buf = new byte[1024]; DatagramPacket packet = new DatagramPacket(buf, buf.length); upnpMulticastSocket.receive(packet); String packetString = new String(packet.getData()); if (isSSDPDiscovery(packetString)) { log.debug( "Got SSDP Discovery packet from " + packet.getAddress().getHostAddress() + ":" + packet.getPort()); sendUpnpResponse(responseSocket, packet.getAddress(), packet.getPort()); } } } catch (IOException e) { log.error("UpnpListener encountered an error. Shutting down", e); ConfigurableApplicationContext context = (ConfigurableApplicationContext) UpnpListener.this.applicationContext; context.close(); } log.info("UPNP Discovery Listener Stopped"); }
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(); }
/** * Copies the properties of a specific <tt>DatagramPacket</tt> to another <tt>DatagramPacket</tt>. * The property values are not cloned. * * @param src the <tt>DatagramPacket</tt> which is to have its properties copied to <tt>dest</tt> * @param dest the <tt>DatagramPacket</tt> which is to have its properties set to the value of the * respective properties of <tt>src</tt> */ public static void copy(DatagramPacket src, DatagramPacket dest) { synchronized (dest) { dest.setAddress(src.getAddress()); dest.setPort(src.getPort()); byte[] srcData = src.getData(); if (srcData == null) dest.setLength(0); else { byte[] destData = dest.getData(); if (destData == null) dest.setLength(0); else { int destOffset = dest.getOffset(); int destLength = destData.length - destOffset; int srcLength = src.getLength(); if (destLength >= srcLength) destLength = srcLength; else if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, "Truncating received DatagramPacket data!"); } System.arraycopy(srcData, src.getOffset(), destData, destOffset, destLength); dest.setLength(destLength); } } } }
public static void doEcho(int port) throws IOException { byte[] buf = new byte[BUF_SIZE]; DatagramPacket packet = new DatagramPacket(buf, buf.length); DatagramSocket sock = new DatagramSocket(port); System.out.println( "Starting UDP echo on" + sock.getLocalAddress().getHostAddress() + ":" + sock.getLocalPort()); while (true) { try { sock.receive(packet); sock.send(packet); System.out.print( "UDP From: " + packet.getAddress().getHostAddress() + ":" + packet.getPort() + "\n" + new String(packet.getData(), 0, packet.getLength()) + "\n"); System.out.flush(); packet.setLength(buf.length); // packet = new DatagramPacket(buf,buf.length); } catch (IOException io_ex) { } } }
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(); } } }
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(); } }
public static void main(String args[]) { DatagramSocket skt = null; try { skt = new DatagramSocket(6789); byte[] buffer = new byte[1000]; while (true) { DatagramPacket request = new DatagramPacket(buffer, buffer.length); skt.receive(request); System.out.println("Data received from client"); System.out.println(new String(request.getData())); Thread.sleep(15000); String[] arrayMsg = (new String(request.getData())).split(" "); System.out.println(arrayMsg[0] + "server processed"); byte[] sendMsg = (arrayMsg[0] + "server processed").getBytes(); DatagramPacket reply = new DatagramPacket(sendMsg, sendMsg.length, request.getAddress(), request.getPort()); System.out.println("sending data from server to client"); Thread.sleep(15000); ; skt.send(reply); } } catch (Exception e) { } }
public void run() { while (moreQuotes) { try { byte[] buf = new byte[256]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // containing IP ecc. // figure out response String dString = null; if (in == null) dString = new Date().toString(); else dString = getNextQuote(); buf = dString.getBytes(); // send the response to the client at "address" and "port" InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); } catch (IOException e) { e.printStackTrace(); moreQuotes = false; } } socket.close(); }
private void listen() throws Exception { System.out.println("Listening on port: " + serverPort); // Initialize socket socket = new DatagramSocket(serverPort); // While running while (run) { // Wait for handshake packet = new DatagramPacket(response, response.length); socket.receive(packet); // Blocking // System.out.println("RT: got packet"); Packet p = new Packet(packet.getData()); if (p.isHandshake()) { // System.out.println("RT: is handshake"); // Get client connection info InetAddress IPAddress = packet.getAddress(); int port = packet.getPort(); // Process handshake processHandshake(p, IPAddress, port); // Get message MyMessage message = getMessage(); if (message != null) { rc.rreceive(message); } } } }
/** Receive loop for private messaqes. Can be stopped with {@link #setRunning(boolean)} */ private void receivePrivateMessages() { while (isRunning()) { try { final byte[] buf = new byte[BUFFER_SIZE]; final DatagramPacket receivePacket = new DatagramPacket(buf, buf.length); if (LOG.isDebugEnabled()) { LOG.debug( "Waiting for private message, listening on port " + privateSocket.getLocalPort()); } privateSocket.receive(receivePacket); // wait for a packet final String data = toString(receivePacket); if (LOG.isDebugEnabled()) { LOG.debug("Got a private message: " + data); } if (LOG.isDebugEnabled()) { LOG.debug( "Received " + data + " from " + receivePacket.getAddress() + ":" + receivePacket.getPort() + "."); } processPrivateMessage(data); } catch (IOException e) { LOG.error(BUNDLE_MARKER, e.toString(), e); } } if (LOG.isDebugEnabled()) { LOG.debug("Stopped listening to private messages."); } }
public static void main(String args[]) throws Exception { String serverHostname = args[0]; int portNumber = Integer.parseInt(args[1]); try { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName(serverHostname); System.out.println("Attempting to connect to " + IPAddress + ") via UDP port " + portNumber); System.out.println("Enter \"Quit\" to exit program"); while (true) { byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; System.out.print("Enter Message: "); String sentence = inFromUser.readLine(); if (sentence.equals("Quit")) break; sendData = sentence.getBytes(); System.out.println("Sending data to " + sendData.length + " bytes to server."); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, portNumber); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); System.out.println("Waiting for return packet"); clientSocket.setSoTimeout(10000); try { clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); InetAddress returnIPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); System.out.println("From server at: " + returnIPAddress + ":" + port); System.out.println("Message: " + modifiedSentence); } catch (SocketTimeoutException ste) { System.out.println("Timeout Occurred: Packet assumed lost"); } System.out.print("\n"); } clientSocket.close(); } catch (UnknownHostException ex) { System.err.println(ex); } catch (IOException ex) { System.err.println(ex); } }
/** * Initializes a new <tt>DatagramPacket</tt> instance which is a clone of a specific * <tt>DatagramPacket</tt> i.e. the properties of the clone <tt>DatagramPacket</tt> are clones of * the specified <tt>DatagramPacket</tt>. * * @param p the <tt>DatagramPacket</tt> to clone * @return a new <tt>DatagramPacket</tt> instance which is a clone of the specified * <tt>DatagramPacket</tt> */ public static DatagramPacket clone(DatagramPacket p) { synchronized (p) { byte[] pData = p.getData(); byte[] cData = (pData == null) ? null : pData.clone(); return new DatagramPacket(cData, p.getOffset(), p.getLength(), p.getAddress(), p.getPort()); } }
/** * Sends a datagram packet to the destination, with a TTL (time- to-live) other than the default * for the socket. This method need only be used in instances where a particular TTL is desired; * otherwise it is preferable to set a TTL once on the socket, and use that default TTL for all * packets. This method does <B>not </B> alter the default TTL for the socket. Its behavior may be * affected by {@code setInterface}. * * <p>If there is a security manager, this method first performs some security checks. First, if * {@code p.getAddress().isMulticastAddress()} is true, this method calls the security manager's * {@code checkMulticast} method with {@code p.getAddress()} and {@code ttl} as its arguments. If * the evaluation of that expression is false, this method instead calls the security manager's * {@code checkConnect} method with arguments {@code p.getAddress().getHostAddress()} and {@code * p.getPort()}. Each call to a security manager method could result in a SecurityException if the * operation is not allowed. * * @param p is the packet to be sent. The packet should contain the destination multicast ip * address and the data to be sent. One does not need to be the member of the group to send * packets to a destination multicast address. * @param ttl optional time to live for multicast packet. default ttl is 1. * @exception IOException is raised if an error occurs i.e error while setting ttl. * @exception SecurityException if a security manager exists and its {@code checkMulticast} or * {@code checkConnect} method doesn't allow the send. * @deprecated Use the following code or its equivalent instead: ...... int ttl = * mcastSocket.getTimeToLive(); mcastSocket.setTimeToLive(newttl); mcastSocket.send(p); * mcastSocket.setTimeToLive(ttl); ...... * @see DatagramSocket#send * @see DatagramSocket#receive * @see SecurityManager#checkMulticast(java.net.InetAddress, byte) * @see SecurityManager#checkConnect */ @Deprecated public void send(DatagramPacket p, byte ttl) throws IOException { if (isClosed()) throw new SocketException("Socket is closed"); checkAddress(p.getAddress(), "send"); synchronized (ttlLock) { synchronized (p) { if (connectState == ST_NOT_CONNECTED) { // Security manager makes sure that the multicast address // is allowed one and that the ttl used is less // than the allowed maxttl. SecurityManager security = System.getSecurityManager(); if (security != null) { if (p.getAddress().isMulticastAddress()) { security.checkMulticast(p.getAddress(), ttl); } else { security.checkConnect(p.getAddress().getHostAddress(), p.getPort()); } } } else { // we're connected InetAddress packetAddress = null; packetAddress = p.getAddress(); if (packetAddress == null) { p.setAddress(connectedAddress); p.setPort(connectedPort); } else if ((!packetAddress.equals(connectedAddress)) || p.getPort() != connectedPort) { throw new SecurityException("connected address and packet address" + " differ"); } } byte dttl = getTTL(); try { if (ttl != dttl) { // set the ttl getImpl().setTTL(ttl); } // call the datagram method to send getImpl().send(p); } finally { // set it back to default if (ttl != dttl) { getImpl().setTTL(dttl); } } } // synch p } // synch ttl } // method
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 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 } }
/** * {@collect.stats} {@description.open} Sends a datagram packet from this socket. The <code> * DatagramPacket</code> includes information indicating the data to be sent, its length, the IP * address of the remote host, and the port number on the remote host. * * <p>If there is a security manager, and the socket is not currently connected to a remote * address, this method first performs some security checks. First, if <code> * p.getAddress().isMulticastAddress()</code> is true, this method calls the security manager's * <code>checkMulticast</code> method with <code>p.getAddress()</code> as its argument. If the * evaluation of that expression is false, this method instead calls the security manager's <code> * checkConnect</code> method with arguments <code>p.getAddress().getHostAddress()</code> and * <code>p.getPort()</code>. Each call to a security manager method could result in a * SecurityException if the operation is not allowed. {@description.close} * * @param p the <code>DatagramPacket</code> to be sent. * @exception IOException if an I/O error occurs. * @exception SecurityException if a security manager exists and its <code>checkMulticast</code> * or <code>checkConnect</code> method doesn't allow the send. * @exception PortUnreachableException may be thrown if the socket is connected to a currently * unreachable destination. Note, there is no guarantee that the exception will be thrown. * @exception java.nio.channels.IllegalBlockingModeException if this socket has an associated * channel, and the channel is in non-blocking mode. * @see java.net.DatagramPacket * @see SecurityManager#checkMulticast(InetAddress) * @see SecurityManager#checkConnect * @revised 1.4 * @spec JSR-51 */ public void send(DatagramPacket p) throws IOException { InetAddress packetAddress = null; synchronized (p) { if (isClosed()) throw new SocketException("Socket is closed"); checkAddress(p.getAddress(), "send"); if (connectState == ST_NOT_CONNECTED) { // check the address is ok wiht the security manager on every send. SecurityManager security = System.getSecurityManager(); // The reason you want to synchronize on datagram packet // is because you dont want an applet to change the address // while you are trying to send the packet for example // after the security check but before the send. if (security != null) { if (p.getAddress().isMulticastAddress()) { security.checkMulticast(p.getAddress()); } else { security.checkConnect(p.getAddress().getHostAddress(), p.getPort()); } } } else { // we're connected packetAddress = p.getAddress(); if (packetAddress == null) { p.setAddress(connectedAddress); p.setPort(connectedPort); } else if ((!packetAddress.equals(connectedAddress)) || p.getPort() != connectedPort) { throw new IllegalArgumentException( "connected address " + "and packet address" + " differ"); } } // Check whether the socket is bound if (!isBound()) bind(new InetSocketAddress(0)); // call the method to send getImpl().send(p); } }
private void readSendPacket(DatagramPacket sendPacket) { // print log System.out.println("Server: sending a packet..."); System.out.println("To host: " + sendPacket.getAddress()); System.out.println("Destination host port: " + sendPacket.getPort()); Request req = new Request(sendPacket.getData(), sendPacket.getLength()); String reqString = req.getString(); byte reqBytes[] = req.getByteArray(); System.out.print("String: '" + reqString + "'\n"); System.out.print("Bytes: '"); int i = 0; while (i < req.getLength()) { System.out.print(reqBytes[i++]); } System.out.print("'\n"); }
private void readReceivePacket(DatagramPacket receivePacket) { // print log Request req = new Request(receivePacket.getData(), receivePacket.getLength()); System.out.println("Server: receiving a packet..."); System.out.println("From host: " + receivePacket.getAddress()); System.out.println("Host port: " + receivePacket.getPort()); String reqString = req.getString(); byte reqBytes[] = req.getByteArray(); System.out.print("String: '" + reqString + "'\n"); System.out.print("Bytes: '"); int i = 0; while (i < req.getLength()) { System.out.print(reqBytes[i++]); } System.out.print("'\n"); System.out.println("Server: packet received.\n"); }
public void run() { try { byte[] in_data = new byte[pkt_size]; DatagramPacket in_pkt = new DatagramPacket(in_data, in_data.length); try { while (true) { sk_in.receive(in_pkt); System.out.print( (new Date().getTime()) + ": sender received " + in_pkt.getLength() + "bytes from " + in_pkt.getAddress().toString() + ":" + in_pkt.getPort() + ". data are "); for (int i = 0; i < pkt_size; ++i) System.out.print(in_data[i]); System.out.println(); try { String res = new String(in_data); String[] arr = new String[2]; arr = res.split(" "); System.out.println(arr[0]); System.out.println(arr[1]); if ((arr[0].trim().equalsIgnoreCase(String.valueOf(curr))) && (arr[1].trim().equalsIgnoreCase("ACK") && (arr[2].trim().equalsIgnoreCase(String.valueOf(617709412))))) { curr++; } } catch (Exception e) { } } } catch (Exception e) { e.printStackTrace(); } finally { sk_in.close(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } }
/** * Main method keeps waiting for request and do math operation accordingly * * @param args */ public static void main(String args[]) { DatagramSocket aSocket = null; try { aSocket = new DatagramSocket(6789); byte[] buffer = new byte[1000]; while (true) { DatagramPacket request = new DatagramPacket(buffer, buffer.length); aSocket.receive(request); // receive byte array of equation and put it in string String equation = new String(request.getData()); String answer = ""; String[] split = equation.split(" "); // parse to integer and calculate String op = split[1]; double var1 = Double.parseDouble(split[0]); double var2 = Double.parseDouble(split[2]); if (op.equals("+")) { answer = Double.toString(var1 + var2); } else if (op.equals("-")) { answer = Double.toString(var1 - var2); } else if (op.toLowerCase().equals("X") || op.toLowerCase().equals("x")) { answer = Double.toString(var1 * var2); } else if (op.equals("/")) { answer = Double.toString(var1 / var2); } // send answer back DatagramPacket reply = new DatagramPacket( answer.getBytes(), (answer.getBytes()).length, request.getAddress(), request.getPort()); aSocket.send(reply); } } catch (SocketException e) { System.out.println("Socket: " + e.getMessage()); } catch (IOException e) { System.out.println("IO: " + e.getMessage()); } finally { if (aSocket != null) { aSocket.close(); } } }
// sends a response to the Client based upon the contents of the receive packet private void reply(DatagramPacket receivedPacket) { // verify the packet byte serverMsg[] = {}; try { Request recReq = new Request(receivedPacket.getData(), receivedPacket.getLength()); if (!recReq.isValid()) { throw new IllegalStateException(); } switch (recReq.getFormat()) { case RRQ: serverMsg = new byte[] {0, 3, 0, 1}; break; case WRQ: serverMsg = new byte[] {0, 4, 0, 0}; break; default: throw new IllegalStateException(); } } catch (IllegalStateException e) { e.printStackTrace(); System.exit(1); } DatagramPacket sendPacket = new DatagramPacket( serverMsg, serverMsg.length, receivedPacket.getAddress(), receivedPacket.getPort()); readSendPacket(sendPacket); try { // Send the datagram packet to the client via the send socket. DatagramSocket sendSocket = new DatagramSocket(); sendSocket.send(sendPacket); sendSocket.close(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } System.out.println("Server: packet sent.\n"); }
public static void main(String[] argv) throws Exception { // ワイルドカードアドレスで待ち受け DatagramSocket datagram_socket = new DatagramSocket(PORT); // 受け付けるデータバッファとUDPパケットを作成 byte buffer[] = new byte[1024]; DatagramPacket datagram_packet = new DatagramPacket(buffer, buffer.length); while (true) { // UDPパケットを受信 datagram_socket.receive(datagram_packet); InetAddress inet_address = datagram_packet.getAddress(); String sender_address = inet_address.getHostAddress(); int sender_port = datagram_packet.getPort(); String received_data = new String(datagram_packet.getData(), 0, datagram_packet.getLength()); // 受信したデータを標準出力へ出力 System.out.println("[" + sender_address + ":" + sender_port + "]" + received_data); } }
public void run() { byte[] buf = new byte[BUF_SIZE]; DatagramPacket incomingData = new DatagramPacket(buf, buf.length); try { while (true) { sock.receive(incomingData); System.out.println( "UDP From:" + incomingData.getAddress().getHostAddress() + ":" + incomingData.getPort()); System.out.println(new String(incomingData.getData(), 0, incomingData.getLength())); System.out.flush(); incomingData.setLength(buf.length); } } catch (IOException io_ex) { io_ex.printStackTrace(); } }
public static void main(String args[]) throws Exception { // Open socket loclahost:6000 DatagramSocket serverSocket = new DatagramSocket(6000, InetAddress.getByName("localhost")); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; // Hanging on while (true) { DatagramPacket readPacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(readPacket); String readData = new String(readPacket.getData()); System.out.println("UDP Server, " + readData); InetAddress ip = readPacket.getAddress(); int port = readPacket.getPort(); String output = "Hello, " + readData; sendData = output.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, port); serverSocket.send(sendPacket); } }
public void run() { System.out.println(" -----------------UDP Demo Server-----------------" + "\n\n"); while (true) { try { // Create a new socket connection bound to the defined port DatagramSocket sock = new DatagramSocket(BROADCAST_PORT); System.out.println("Waiting for data on local port: " + sock.getLocalPort()); // Create a packet to contain incoming data byte[] buf = new byte[256]; DatagramPacket packet = new DatagramPacket(buf, buf.length); // Wait for incoming data (receive() is a blocking method) sock.receive(packet); // Retrieve data from packet and display String data = new String(packet.getData()); int endIndex = data.indexOf(0); data = data.substring(0, endIndex); int remotePort = packet.getPort(); System.out.println("Received data from remote port " + remotePort + ":\n" + data); // Determine origin of packet and display information InetAddress remoteAddress = packet.getAddress(); System.out.println("Sent from address: " + remoteAddress.getHostAddress()); // Send back an acknowledgment String ack = "RECEIVED " + new Date().toString(); sock.send(new DatagramPacket(ack.getBytes(), ack.length(), remoteAddress, remotePort)); sock.close(); } catch (IOException ioe) { System.out.println("Error: IOException - " + ioe.toString()); } } }
/** * Repeatedly receive a packet from the group, process it. No messages are sent from here. * sendPacket(). */ public void receiveGroupMessages() { if (LOG.isDebugEnabled()) { LOG.debug("Starting group receive loop for " + nodeId); } while (this.isRunning()) { try { final byte[] data = new byte[BUFFER_SIZE]; // set up an empty packet final DatagramPacket packet = new DatagramPacket(data, data.length); if (LOG.isDebugEnabled()) { LOG.debug("Waiting for group message on " + groupSocket); } groupSocket.receive(packet); // wait for a packet final String msg = toString(packet); if (LOG.isDebugEnabled()) { LOG.debug( "Received group msg " + msg + " from " + packet.getAddress() + ":" + packet.getPort() + "."); } processGroupMessage(msg); } catch (SocketTimeoutException e) { if (LOG.isInfoEnabled()) { LOG.info(BUNDLE_MARKER, "GroupSocket receive timed out."); } } catch (IOException e) { LOG.error(BUNDLE_MARKER, e.toString(), e); } catch (Throwable t) { LOG.error(BUNDLE_MARKER, t.toString(), t); } } if (LOG.isDebugEnabled()) { LOG.debug("Group receive loop for " + nodeId + " was stopped."); } }
/** * Log the packet. * * @param p packet to log */ @Override protected void doLogPacket(DatagramPacket p) { if (socket.getLocalAddress() == null) return; // Do not log the packet if this one has been processed (and already // logged) by the ice4j stack. if (socket instanceof MultiplexingDatagramSocket) return; PacketLoggingService pktLogging = getPacketLoggingService(); if (pktLogging != null) { pktLogging.logPacket( PacketLoggingService.ProtocolName.RTP, p.getAddress().getAddress(), p.getPort(), socket.getLocalAddress().getAddress(), socket.getLocalPort(), PacketLoggingService.TransportName.UDP, false, p.getData(), p.getOffset(), p.getLength()); } }
@Override public int peekData(DatagramPacket pack) throws IOException { doRecv(pack, MSG_PEEK); return pack.getPort(); }
@Override public void send(DatagramPacket packet) throws IOException { int port = isNativeConnected ? 0 : packet.getPort(); InetAddress address = isNativeConnected ? null : packet.getAddress(); IoBridge.sendto(fd, packet.getData(), packet.getOffset(), packet.getLength(), 0, address, port); }