初识Tomcat
服务端:
自定义 S
Tomcat服务器 S
客户端:
自定义 C
浏览器 B
UDP
相当于发短信:不需要连接服务器,需要知道对方的地址。
发送消息
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
//不需要连接数据库
public class UdpClientDemo01 {
public static void main(String[] args) throws Exception {
//建立一个scoket
DatagramSocket socket = new DatagramSocket();
//建立包
String msg="你好服务器";
InetAddress localhost = InetAddress.getByName("localhost");
int port=9090;
//数据 数据的长度 数据要发送给谁 建立地址 端口
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
//发送包
socket.send(datagramPacket);
//关闭资源
socket.close();
}
}
接收端:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpServerDemo01 {
public static void main(String[] args) throws Exception {
//开放端口
DatagramSocket socket = new DatagramSocket(9090);
//接受包
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
//阻塞接收
socket.receive(packet);
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
//关闭资源
socket.close();
}
}