UDP :不安全的 不需要建立连接通道,执行效率高,发送文件有限制不超过 64kb,线程不同步,
TCP:安全的执行效率第,需要建立连接通道,可靠的连接,发送数据以 字节流发数据,对TCP来说不受限制
UDP:代码实现
import java.io.IOException;
import java.net.*;
public class day1 {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket=new DatagramSocket();
byte[]arr="hello".getBytes();
int br=arr.length;
DatagramPacket da=new DatagramPacket(arr,br, InetAddress.getByName("127.0.0.1"),1086);
datagramSocket.send(da);
datagramSocket.close();
}
}
class day2{
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket=new DatagramSocket(1086);
byte[]arr=new byte[1024];
int ac=arr.length;
DatagramPacket datagramPacket=new DatagramPacket(arr,ac);
datagramSocket.receive(datagramPacket);
byte[] data = datagramPacket.getData();
int length = datagramPacket.getLength();
System.out.println(new String(data,0,length));
}
}
TCP:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class day1 {
public static void main(String[] args) throws InterruptedException, IOException {
Socket socket=new Socket("127.0.0.1",1024);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("张三".getBytes());
}
}
class app{
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=new ServerSocket(1024);
Socket accept = serverSocket.accept();
InputStream inputStream = accept.getInputStream();
byte arr[]=new byte[1024];
int read = inputStream.read(arr);
System.out.println(new String(arr,0,read));
}
}