import java.net.*;
import java.io.*;
public class UDPReceive extends Thread{
DatagramSocket ds;
InetAddress inetAdd;
public UDPReceive(){
}
public void receive(){
byte[] buf =new byte[512];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
try{
ds=new DatagramSocket(3003);
while(true){
ds.receive(dp);
String str =new String(buf,0,dp.getLength());
System.out.println(dp.getAddress()+ "SAY: "+str);
}
}catch(Exception ex){ex.printStackTrace();}
}
public static void main(String[] args){
new UDPReceive().receive();
}
}
------------------------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.net.*;
import java.io.*;
public class UDPSend {
DatagramSocket ds;
BufferedReader br;
byte[] buf;
DatagramPacket dp;
public UDPSend(){
try{
ds=new DatagramSocket(5001);
}catch(Exception ex){ex.printStackTrace();}
}
public static void main(String[] args){
UDPSend udpsend=new UDPSend();
udpsend.send();
}
public void send(){
try {
while(true){
br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
buf=str.getBytes();
dp = new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),3003);
ds.send(dp);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {ds.close();br.close();}catch (IOException e) {e.printStackTrace();}
}
}
}
------解决方案--------------------
因为5001 被第一个占用了
你ds=new DatagramSocket();不填写端口的话
程序会自己选一个,这样就不会出错了