receivedatagram.java

来自「datagram application(basee on server-cli」· Java 代码 · 共 60 行

JAVA
60
字号
/* ReceiveDatagram.java 
*
*  Author: Terry Ridge
*
*  Permission to use, copy, modify, and distribute
*  this software for NON_COMMERCIAL purposes and without
*  fee is hereby granted provided that this copyright notice
*  appears in all copies.
*
*  The creators of this software make no representations or
*  warranties about the suitability of the software, either
*  express or implied.  The creators shall not be liable for
*  any damages suffered by licensee as a result of using,
*  modifying or distributing this software or its derivatives.
*/

import java.io.*;
import java.net.*;

public class ReceiveDatagram
   {

   public static void main(String[] args)
      {
      byte buffer[] = new byte[256];
      String message;
      int port=2222;
/*
      if (args.length != 1)
         {
         System.out.println("Usage: java ReceiveDatagram <port>");
         System.exit(0);
         }

      port = Integer.parseInt(args[0]);
*/
      try
         {
         DatagramPacket receivePacket =
            new DatagramPacket(buffer, buffer.length);

         DatagramSocket socket = new DatagramSocket(port);
		 System.out.println("Port to receive is: "+port);
         while (true)
            {
            socket.receive(receivePacket);
			byte data []=receivePacket.getData();
            message = new String(data, 0, 0, receivePacket.getLength());
            System.out.println("Message received: " + message);
            }
          }
      catch (IOException e)
         {
         System.err.println("Error receiving datagram: " + e);
         }
      }
   }


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?