网络编程三要素
IP,端口,协议
InetAddress
说明 | 方法名 |
确定主机名称的IP地址。主机名称可以是机器名称,也可以是IP地址 | static InetAddress getByName(String host) |
获取此IP地址的主机名 | String getHostName() |
返回文本显示中的IP地址字符串 | String getHostAddress() |
端口
其中,0~1023之间的端口号用于一些知名的网络服务和应用,普通的应用程序需要使用1024以上的端口号
协议
UDP 用户数据报协议(User Datagram Protocol)
- UDP是无连接通信协议,即在数据传输时,数据的发送端和接收端不建立逻辑连接
- 消耗系统资源小,通信效率高,大小有限制64k
//UDP发送
public class ClientDemo {
public static void main(String[] args) throws IOException {
//1.找码头
DatagramSocket ds = new DatagramSocket();
//2.打包礼物
//DatagramPacket(byte[] buf, int length, InetAddress address, int port)
String s = "送给村长老丈人的礼物";
byte[] bytes = s.getBytes();
InetAddress address = InetAddress.getByName("127.0.0.1");
int port = 10000;
DatagramPacket dp = new DatagramPacket(bytes,bytes.length,address,port);
//3.由码头发送包裹
ds.send(dp);
//4.付钱走羊
ds.close();
}
}
//UDP接收
public class ServerDemo {
//注意点:
//1.要先运行接收端,再运行发送端
//2.如果接收端再启动之后,没有接收到数据,那么会死等(阻塞).
//3.在接收数据的时候,需要调用一个getLength方法,表示接收到了多少字节
public static void main(String[] args) throws IOException {
//1.找码头 ---- 表示接收端从10000端口接收数据的.
DatagramSocket ds = new DatagramSocket(10000);
//2,创建一个新的箱子
byte [] bytes = new byte[1024];
DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
//3.接收礼物,把礼物放到新的箱子中
System.out.println("-----------接收前----------");
ds.receive(dp);
System.out.println("------------接收后---------");
//4.从新的箱子里面获取礼物
// byte[] data = dp.getData();
int length = dp.getLength();
System.out.println(new String(bytes,0,length));
//5.拿完走羊
ds.close();
}
}
TCP 传输控制协议 (Transmission Control Protocol)
- TCP协议是面向连接的通信协议,即传输数据之前,在发送端和接收端建立逻辑连接,然后再传输数据
- 它提供了两台计算机之间可靠无差错的数据传输
- 数据传输没有大小限制
- 占用资源比较多,效率比较低
//TCP发送端
public class ClientDemo {
public static void main(String[] args) throws IOException {
//1.使用Socket对象与服务器端建立连接
Socket socket = new Socket("127.0.0.1",10001);
//2.使用Scoket对象获得输出流对象
OutputStream os = socket.getOutputStream();
//3.使用输出流对象发送数据
os.write("hello".getBytes());
//4.关闭连接,释放资源
os.close();
socket.close();
}
}
//TCP接收端
public class ServerDemo {
public static void main(String[] args) throws IOException {
//1. 创建Socket对象
ServerSocket ss = new ServerSocket(10001);
//2. 等待客户端连接
Socket accept = ss.accept();
//3.获得输入流对象
InputStream is = accept.getInputStream();
int b;
while((b = is.read()) != -1){
System.out.print((char) b);//此时,接收中文会乱码,后面会处理
}
//4.释放资源
is.close();
ss.close();
}
}
三次握手
四次挥手