* B 端
* 功能:与A端通信
*
*/
package com.qq.socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDP2 {
public static void main(String[] args) throws IOException {
DatagramSocket udpsocket =null;
DatagramPacket packet =null;
InetAddress address =null;
int port = 0;
udpsocket = new DatagramSocket(8888);
//System.out.println("B开启本地9999端口号");
byte [] buf = new byte[256];
try {
address = InetAddress.getByName("localhost");//给出接收方地址
port =9999;
buf="从B端发送信息,你好A,我是B哥".getBytes();//构造发送数据包
packet = new DatagramPacket(buf, buf.length, address, port);
udpsocket.send(packet);
Thread.sleep(1000);
packet = new DatagramPacket(buf, buf.length);
udpsocket.receive(packet);
System.out.println("接受的数据"+new String (packet.getData()));
address = packet.getAddress();
port = packet.getPort();
System.out.println("请求端socket"+address.toString()+":"+port);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
udpsocket.close();
}
}
/**
* A 端
* 功能:实现udp通信 与 B端通信
* 编程者:张波
*
*/
package com.qq.socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPSocket {
public static void main(String []args) throws IOException{
DatagramSocket udpsocket = null;//创建一个DatagramSocket
InetAddress address=null;
DatagramPacket packet =null;
int port =0;
udpsocket= new DatagramSocket(9999);
System.out.println("A开启本地UDP9999端口");
byte [] buf =new byte[256];
try {
packet = new DatagramPacket(buf, buf.length);
udpsocket.receive(packet);//接收数据
System.out.println("接受的数据:"+ " "+new String (packet.getData()));
Thread.sleep(1000);
address =packet.getAddress();
port = packet.getPort();
System.out.println("请求端Socket"+address.toString()+":"+port);
buf="A端信息".getBytes();
packet=new DatagramPacket(buf, buf.length, address, port);
udpsocket.send(packet);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
udpsocket.close();
}
}