<pre name="code" class="html">package blog_UDP;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class TalkDemo {
public static void main(String[] args) throws SocketException {
DatagramSocket send = new DatagramSocket(8888);
DatagramSocket reveive = new DatagramSocket(8900);
new Thread(new Sender(send)).start();
new Thread(new Reveiver(reveive)).start();
}
}
class Sender implements Runnable
{
private DatagramSocket ds;
public Sender(DatagramSocket ds)
{
super();
this.ds = ds;
}
public void run()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String data = null;
try {
while((data = br.readLine())!=null){
byte [] buff = data.getBytes();
DatagramPacket p = new DatagramPacket(buff, buff.length,
InetAddress.getByName("10.10.216.135"), 8900);
ds.send(p );
if(data.equals("over"))
break;
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Reveiver implements Runnable
{
private DatagramSocket ds;
public Reveiver(DatagramSocket ds)
{
super();
this.ds = ds;
}
public void run()
{
byte [] buff = new byte[1024];
DatagramPacket p = new DatagramPacket(buff,buff.length);
try {
while(true){
ds.receive(p );
String ip = p.getAddress().getHostAddress();
int port = p.getPort();
String dat =new String(p.getData(),0,p.getLength());
if("over".equals(dat))
System.out.println("ip----"+ ip+"离开了。。。");
else{
System.out.println("ip----"+ ip +"----发送的数据为: "+ dat);
System.out.println("port为 :"+ port);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果为:
<img src="https://img-blog.csdn.net/20150505162532892" alt="" />