TCP、UDP协议
1.1、网络通信要素
1.网络编程中两个主要问题
- 如何准确定位到网络上的一台主机或者多台主机
- 找到主机之后如何进行通信
2.网络编程中的要素
- IP和端口号
- 网络通信协议 UDP、TCP
1.2、IP
含义:
ip(InetAdsress)唯一定位一台网络上计算机
本机地址:127.0.0.1,localhost
import java.net.InetAddress;
import java.net.UnknownHostException;
//测试IP
public class TestInetAddress {
public static void main(String[] args) throws UnknownHostException {
InetAddress inetAddress =InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress);
InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress2);
//常用方法
System.out.println(inetAddress2.getAddress());
System.out.println(inetAddress2.getCanonicalHostName());
System.out.println(inetAddress2.getHostAddress());
}
}
1.3、端口
端口表示计算机上的一个程序的进程;
不同的进程有不同的端口号(范围被规定为0-65535)
#查看所有端口
netstat -ano
#查看指定的端口
netstat -ano findstr “3306”
# 查看指定端口的进程
Ctrl+shift+ESC(打开任务管理器)
1.4、通信协议
协议:约定
网络通信协议:速率、传输码率、代码结构、传输控制。。
TCP/IP协议簇:实际上是一组协议
TCP:用户传输协议
UDP:用户数据报协议
IP:网络互联协议
TCP-UDP对比
TCP :
- 连接、稳定
三次握手
、四次挥手
- 客户端、服务端
- 传输完成、释放连接、效率低
UDP:
- 不连接,不稳定
- 客户端、服务端:没有明确的界限
- 不管有没有准备好都可以发给你
1.5、TCP
客户端、服务端通信
- 客户端
// 客户端
public class TcpClient {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
//1.创建Socket对象,指明服务器端的ip和端口号
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet, 8899);
//2.获取一个输出流,用于输出数据
os = socket.getOutputStream();
//3.写出数据的操作
os.write("你好,我是客户端mm".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源的关闭
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 服务端
// 服务端
public class TcpServer {
public static void main(String[] args) {
ServerSocket ss = null;
Socket socket = null;
InputStream is = null