UDP編程中,為什麼服務器不能向客戶端發送消息呢,客戶端也不能接收服務器發送的消息?
服務器代碼:
import java.net.*;
public class Server2 {
public static void main(String[] args) {
try {
//向客戶端發送消息
byte[] b="我是服務器".getBytes();
InetAddress ia= InetAddress.getByName("localhost");
DatagramPacket dp=new DatagramPacket(b,b.length,ia,9999);
DatagramSocket ds =new DatagramSocket();
ds.send(dp);
//接收從客戶端發送的數據
byte[] b2=new byte[1024];
DatagramPacket dp2=new DatagramPacket(b2,b2.length);
DatagramSocket ds2 =new DatagramSocket(9438);
ds2.receive(dp2);
//打印客戶端發送的數據
System.out.println(new String(b2,0,b2.length));
ds.close();
ds2.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客戶端代碼:
import java.net.*;
public class Client2 {
public static void main(String[] args) {
try {
//向服務器發送數據
byte b[]="我是客戶端".getBytes();
InetAddress ia = InetAddress.getByName("localhost");
DatagramPacket dp=new DatagramPacket(b,b.length,ia,9438);
DatagramSocket ds=new DatagramSocket();
ds.send(dp);
//接收從服務器發送的消息
byte b2[]=new byte [1024];
DatagramPacket dp2=new DatagramPacket(b2,b2.length);
DatagramSocket ds2=new DatagramSocket(9999);
ds2.receive(dp2);
//打印服務器發送的數據
System.out.println("呵呵");
System.out.println(new String(b2,0,b2.length));
ds.close();
ds2.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
http://blog.csdn.net/zlqqhs/article/details/8759042
參考