* 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();
}
}