DatagramPacket DatagramSocket

  • Post author:
  • Post category:其他


//接收数据

import java.net.*;

public class UDPTestServer

{


public static void main(String[] args) throws Exception

{


byte[] buffer = new byte[8192];

DatagramPacket dp = new DatagramPacket(buffer, buffer.length);

DatagramSocket server = new DatagramSocket(5678);

server.receive(dp);

String s = new String(dp.getData(),dp.getOffset(),dp.getLength());

System.out.println(s);

}

}

//发送数据

import java.io.IOException;

import java.net.*;

public class UDPTestClient {


public static void main(String[] args) throws IOException {


String s=”This is just a test”;

byte[] buf = s.getBytes();

InetAddress add = InetAddress.getByName(“127.0.0.1”);

DatagramPacket dp = new DatagramPacket(buf,buf.length,add,5678);

DatagramSocket theSocket = new DatagramSocket();

theSocket.send(dp);

}

}



版权声明:本文为majcos原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。