TCP(Transmission Control Protocol)
传输控制协议,是一种面向连接的,可靠的,基于字节流的传输层通信协议,TCP层位于IP层之上,应用层之下的中间层。TCP保障了两个应用程序之间的可靠通信。通常用于互联网协议,被称为TCP / IP
UDP(User Datagram Protocol)
用户数据报协议,位于OSI模型的传输层。一个无连接的协议。提供了应用程序之间要发送数据的数据报。由于UDP缺乏可靠性且属于无连接协议,所以应用程序通信必须容许一些丢失,错误或重复的数据包
DatagramPacket 类(UDP)
服务端
public class Socket_S {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(6666);
DatagramPacket datagramPacket = new DatagramPacket(new byte[1024*8],8192);
datagramSocket.receive(datagramPacket);
byte[] data = datagramPacket.getData();
int length = datagramPacket.getLength();
String str = new String(data,0,length);
System.out.println(str);
}
}
客户端
public class Socket_B {
public static void main(String[] args) throws IOException {
//建立数据起始
DatagramSocket datagramSocket = new DatagramSocket(9999);
String msg = "hello world";
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(StandardCharsets.UTF_8),
msg.getBytes(StandardCharsets.UTF_8).length,
InetAddress.getByName("127.0.0.1"),6666);
datagramSocket.send(datagramPacket);
}
}
Socket类 和 ServerSocket(TCP)
服务器应用程序通过使用 java.net.ServerSocket 类以获取一个端口,并且侦听客户端请求服务器端
public class Server_ {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
File file = new File("F:\\map.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1){
fileOutputStream.write(bytes,0,len);
}
serverSocket.close();
}
}
客户端
public class Client_ {
public static void main(String[] args) throws IOException {
String adr = "127.0.0.1";
int port = 9999;
File file = new File("F:/map.txt");
FileInputStream fileInputStream = new FileInputStream(file);
Socket socket = new Socket(adr,port);
byte[] bytes = new byte[1024];
int len = 0;
OutputStream outputStream = socket.getOutputStream();
while ((len = fileInputStream.read(bytes)) != -1){
outputStream.write(bytes,0,len);
}
socket.shutdownOutput();
}
}