udp通信
接收端 的编写步骤:
1、新建套接 DatagramSocket 并绑定相应端口
2、新建DatagramPackt 用于接收从发送端传过来的数据包
3、调用receive方法接收
package com.ldl.udptest;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceive {
public static void main(String[] args) {
DatagramSocket ds = null;
try{
ds = new DatagramSocket(20000); //监听端口号
while(true){
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length); //
ds.receive(dp); //单用receive方法接收
buf = dp.getData();
String data = new String(buf, 0, dp.getLength());
System.out.println(data);
// System.out.println("data:"+data+" port:"+port+" ip:"+ip);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(ds!=null){
ds.close(); //关闭套接字
}
}
}
}
发送端
package com.ldl.udptest;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpSend {
public static void main(String[] args) {
BufferedReader br = null;
DatagramSocket ds = null;
try{
ds = new DatagramSocket();
while(true){
br = new BufferedReader(new InputStreamReader(System.in)); //新建一个缓冲流读取键盘输入
byte[] buf = new byte[1024]; //由于DatagramPacket中需要byte参数
buf = br.readLine().getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.191.2"),20000);//四个参数分别是读取到输入的数组,数组长度,接收端IP地址,端口号
ds.send(dp); //调用send方法发送
InetAddress ip = InetAddress.getLocalHost(); //获取本地IP
// System.out.println("本机的IP地址为:"+ip);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(ds !=null){
ds.close();
}
}
}
}