网络连接有三要素,分别是IP地址,端口和协议。而协议分两种分别是UDP和TCP。UDP是无联通的通信协议,即在数据传输时数据的发送端和接收端不建立连接,由于UDP消耗资源小,通信效率高,所以会用于音频,视频和普通数据的传输。但是由于UDP面向无连接不能确保数据的完整性,所以当传输重要数据是不建议用UDP。下面就是如何用UDP发送数据。
在这里插入代码片
```import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class Clss {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket ();
Scanner sc = new Scanner ( System.in );
String line;
while ((line = sc.nextLine ()) != null) {
if ("over".equals ( line )) {
break;
}
DatagramPacket dp = new DatagramPacket ( line.getBytes () ,
line.getBytes ().length , InetAddress.getByName ( "127.0.0.1" ) ,
12345 );
ds.send ( dp );
}
ds.close ();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class DEmo {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket ( 12345 );
while (true) {
byte[] bytes = new byte[8192];
DatagramPacket dp = new DatagramPacket ( bytes , bytes.length );
ds.receive ( dp );
InetAddress address = dp.getAddress ();
String host = "未知IP";
if (address != null) {
host = address.getHostAddress ();
}
byte[] data = dp.getData ();
int length = dp.getLength ();
String date = new String ( data , 0 , length );
System.out.println ( host + "说:" + date );
}
}
}
//这个代码实现的就是UDP的数据连接。