Java网络编程DatagramPacket传数据

客户端

package CH05;



import java.net.InetAddress;
import java.net.DatagramPacket;
import java.net.MulticastSocket;


public class Client
{
public static void main(String [] arstring) 
  {
  try 
    {
      byte [] arb = new byte [] {'h','e','l','l','o'}; 
      InetAddress inetAddress = InetAddress.getByName("230.0.0.1"); 
      DatagramPacket datagramPacket = new DatagramPacket(arb, arb.length, inetAddress, 7777); 
      MulticastSocket multicastSocket = new MulticastSocket(); 
      multicastSocket.send(datagramPacket); 
    } 
    catch (Exception exception) 
    {
    exception.printStackTrace(); 
    } 
  } 




服务端

package CH05;


import java.net.InetAddress;
import java.net.DatagramPacket;
import java.net.MulticastSocket;


public class Server 
{
public static void main(String [] arstring)
  {
  try 
    {
   MulticastSocket multicastSocket = new MulticastSocket(7777); 
   InetAddress inetAddress = InetAddress.getByName("230.0.0.1"); 
   multicastSocket.joinGroup(inetAddress);  
   while (true) 
   {
    byte [] arb = new byte [100]; 
     DatagramPacket datagramPacket = new DatagramPacket(arb, arb.length); 
       multicastSocket.receive(datagramPacket); 
     System.out.println(new String(arb)); 
      } 
    } 
    catch (Exception exception) 
    {
    exception.printStackTrace(); 
    } 
  } 

你可能感兴趣的:(【后端知识】)