udp:要考虑数据包的大小,防止数据丢失。64K大小
接收端:
DatagramSocket socket = new DatagramSocket(9090);
//准备空的数据包用于存放数据。
byte[] buf = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length); // 1024
//调用udp的服务接收数据
socket.receive(datagramPacket);
socket.close();
发送端:
DatagramSocket datagramSocket = new DatagramSocket();
//准备数据,把数据封装到数据包中。
String data = "这个是我第一个udp的例子..";
//创建了一个数据包
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.getBytes().length,InetAddress.getLocalHost() , 9090);
//调用udp的服务发送数据包
datagramSocket.send(packet);
//关闭资源 ---实际上就是释放占用的端口号
datagramSocket.close();
udp实现群聊加
`BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
String line = null;
DatagramPacket packet = null;
while((line = keyReader.readLine())!=null){
packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("192.168.15.255"), 9090);
socket.send(packet)`
boolean flag = true;
while(flag){
socket.receive(packet);
System.out.println(packet.getAddress().getHostAddress()+"˵:"+new String(buf,0,packet.getLength()));
}
tcp:三次握手
Socket socket = new Socket(InetAddress.getLocalHost(),9090);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("aaa".getBytes());
InputStream inputStream = socket.getInputStream();
byte[] buf = new byte[1024];
int length = inputStream.read(buf);
System.out.println("aaa"+ new String(buf,0,length));
socket.close();
ServerSocket serverSocket = new ServerSocket(9090);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
byte[] buf = new byte[1024];
int length = 0;
length = inputStream.read(buf);
System.out.println("bbb"+ new String(buf,0,length));
OutputStream outputStream = socket.getOutputStream();
outputStream.write("aaa".getBytes());
serverSocket.close();
tomcat:
OutputStream outputStream = socket.getOutputStream();
outputStream.write("<html><head><title>aaa</title></head><body>w</body></html>".getBytes());
socket.close();
ServerSocket serverSocket = new ServerSocket(9090);
while(true){
Socket socket = serverSocket.accept();
new TomcatDemo(socket).start();
}