请求数据格式:
请求行:请求方法(get、post)、url(/首页)http协议 请求第一行
请求头
格式:key:value 第二行
请求体get内容在请求行
post在请求体
响应行http协议,状态码
响应头key:value
响应体:存放服务器给客户端的内容
网络编程3要素
1.iP地址 确定对方主机
2.端口号 区分引用程序
3.协议:tcp/udp
公网带宽限制(1m:28kb/s)
package scoket; import java.net.InetAddress; import java.net.UnknownHostException; /** * **/ public class Demo01 { public static void main(String[] args) throws UnknownHostException { //获取主机名的ip地址,host参数表示指定主机 InetAddress inetAddress = InetAddress.getByName("localhost"); String hostName = inetAddress.getHostName(); System.out.println("hostname:"+hostName);//localhost String hostAddress = inetAddress.getHostAddress(); System.out.println("hostAddress:"+hostAddress); } }
hostNanme:域名
面向无连接。udp会把数据打包发送到目标地址,这个数据包能不能发送到目标地址就不管了,所以我们的udp协议不可靠,容易丢包,但是速度快。
package scoket; import java.io.IOException; import java.net.*; import java.nio.charset.StandardCharsets; /** * **/ public class UdpClient { public static void main(String[] args) throws IOException { //发送数据 DatagramSocket datagramSocket = new DatagramSocket(8888); byte[] msg="mayikt".getBytes(); InetAddress localhost = InetAddress.getByName("localhost"); int port=8080; DatagramPacket datagramPacket = new DatagramPacket(msg,msg.length,localhost,port); datagramSocket.send(datagramPacket); System.out.println("发送数据成功"); //接收数据 byte[] bytes = new byte[1024]; DatagramPacket datagramPacket1 = new DatagramPacket(bytes, bytes.length); //开始监听客户端发送数据,如果没有发,代码一直阻塞 System.out.println("开始接收数据...."); datagramSocket.receive(datagramPacket1); System.out.println("接收到数据..."); byte[] data = datagramPacket.getData(); String msg1= new String(data,0,datagramPacket1.getLength()); System.out.println(msg1); } }
package scoket; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; /** * **/ public class UDPservice { public static void main(String[] args) throws IOException { DatagramSocket datagramSocket = new DatagramSocket(8080); //接收数据 byte[] bytes = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length); //开始监听客户端发送数据,如果没有发,代码一直阻塞 System.out.println("开始接收数据...."); datagramSocket.receive(datagramPacket); System.out.println("接收到数据..."); byte[] data = datagramPacket.getData(); String msg= new String(data,0,datagramPacket.getLength()); System.out.println(msg); //发送数据 byte[] msg1="mayikt".getBytes(); InetAddress localhost = InetAddress.getByName("localhost"); int port=8888; DatagramPacket datagramPacket1 = new DatagramPacket(msg1,msg1.length,localhost,port); datagramSocket.send(datagramPacket1); System.out.println("发送数据成功"); } }