UDP网络通讯简单例子(发包模式不需要建立通路)

package ceshi;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class UDPSocket {

/**
* UDP传输不需要确定是否建立通路
* 发送数据方法
* @param args
* @throws Exception
*/ 
public static void main1(String[] args) throws Exception {

// 创建udp服务
DatagramSocket ds = new DatagramSocket();

//以下代码循环获取数据,对应下面注释循环接受
// BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
// String line = null;
// while((line=br.readLine())!=null){
// if(line.equals("null")){
// break;
// }
// byte[] by = line.getBytes();
// DatagramPacket dp = new DatagramPacket(by, by.length, InetAddress.getByName("192.168.0.144"), 8080);
// ds.send(dp);
// }
// ds.close();



// 确定数据
byte[] by = "数据内容".getBytes();
// 封装成包
DatagramPacket dp = new DatagramPacket(by, by.length, InetAddress.getByName("192.168.0.144"), 8080);
// 铜鼓socket发送数据
ds.send(dp);

ds.close();

}

public static void main(String[] args) throws Exception {
// 创建udp,建立端点
DatagramSocket ds = new DatagramSocket(8080);


// 循环接受的话在这里介入
// while (true) {
// 将下面全部包括
// }

// 定义数据包储存数据
byte[] by = new byte[1024];
DatagramPacket dp = new DatagramPacket(by, by.length);
// 通过receive方法将数据放入包中
ds.receive(dp);


// 通过数据包的方法取出数据
String ip = dp.getAddress().getHostAddress();

String data = new String(dp.getData(), 0, dp.getLength());

int port = dp.getPort();//端口

System.out.println("ip:"+ip+"data:"+data+"port:"+port);

ds.close();
}
}

猜你喜欢

转载自blog.csdn.net/qq_34495753/article/details/80609774