我自己写的代码:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UdpRecvDemo
{
public static void main(String[] args) throws IOException
{
Recv();
}
public static void Recv() throws IOException
{
System.out.println("接受开始......");
DatagramSocket ds = new DatagramSocket(3388);
while(true)
{
byte[]buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
System.out.println(ds);
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
String text = new String(dp.getData(),0,dp.getLength());
if(text.equals("exit"))
{
System.out.println(ip+"退出会话......");
break;
}
System.out.println(ip+":"+port+"===>me "+text);
}
ds.close();
}
}