receiver.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Arrays;
// Server side
public class receiver
{
public static void main(String[] args) throws IOException
{
DatagramPacket receive = new DatagramPacket(new byte[1024], 1024);
DatagramSocket server = new DatagramSocket(8888);
System.out.println("---------------------------------");
System.out.println("Server current start......");
System.out.println("---------------------------------");
while (true)
{
server.receive(receive);
byte[] recvByte = Arrays.copyOfRange(receive.getData(), 0,
receive.getLength());
System.out.println("Server receive msg:" + new String(recvByte));
}
}
}
sender.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
// Client
public class sender
{
public static void main(String[] args) throws IOException
{
byte[] msg = new String("connection successfully!!!").getBytes();
// The local broadcast address is used here
InetAddress inetAddr = InetAddress.getByName("255.255.255.255");
DatagramSocket client = new DatagramSocket();
DatagramPacket sendPack = new DatagramPacket(msg, msg.length, inetAddr,
8888);
client.send(sendPack);
System.out.println("Client send msg complete");
client.close();
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.