网络编程之UDP协议学习

来源:互联网 发布:html5 720度全景 js 编辑:程序博客网 时间:2024/06/05 18:05
/**
 * 发送端:
 * 1.建立udpSocket服务
 * 2.提供数据,并将数据封装到数据包中
 * 3.通过socket服务的发送功能,将数据发送出去
 * 4.关闭服务
 * @author qiuzhiwen
 *
 */
class Send implements Runnable{

private DatagramSocket ds;
public Send(DatagramSocket ds){
this.ds=ds;
}


@Override
public void run() {
try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String line=null;
while((line=br.readLine())!=null){
if("886".equals(line))
break;
byte[] buf=line.getBytes();
DatagramPacket dp=new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.155.8"), 10003);
ds.send(dp);
//ds.close();
}
} catch (Exception e) {
throw new RuntimeException("发送端异常!");
}
}

}


/**
 * 接收端:
 * 1.定义udpSocket服务
 * 2.定义一个数据包,存储接收到的字节数据,可以提取字节数据中的不同数据
 * 3.接收数据receive方法
 * 4.提取数据
 * 5.关闭服务
 * @author qiuzhiwen
 *
 */
class Receive implements Runnable{
private DatagramSocket ds;
public  Receive(DatagramSocket ds){
this.ds=ds;
}


@Override
public void run() {
try {
while(true){
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf, buf.length);
ds.receive(dp);

String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"::"+data);
//ds.close();
}
} catch (Exception e) {
throw new RuntimeException("接收端异常!");
}
}
}


/**
 * 主线程
 * @author qiuzhiwen
 *
 */
public class WeChat {
public static void main(String[] args) {
try {
DatagramSocket sendSocket=new DatagramSocket();
DatagramSocket receiveSocket=new DatagramSocket(10003);
//开启两个线程
new Thread(new Send(sendSocket)).start();
new Thread(new Receive(receiveSocket)).start();
} catch (Exception e) {
throw new RuntimeException("异常!!");
}
}


}
原创粉丝点击