网络编程
概述
-
主要问题
- 如何准确的定位网络上一台或多台主机;定位主机上的特定的应用.
- 找到主机后如何可靠高效地进行数据传输
-
网络编程中的两个要素:
- 对应问题一:IP和端口号
- 对应问题二:提供网络通信协议:TCP/IP参考模型(应用层,传输层,网略层,物理+数据链路层)
-
通信要素一:IP和端口号
- IP:唯一的标识Internet上的计算机(通信实体)
- 在java中使用InetAddress类代表IP
- IP分类:IPv4和IPv6;万维网和局域网
- 域名:www.baidu.com
- 本地地址:127.0.0.1 对应着:localhost
-
端口号:正在计算机上运行的程序
- 要求:不同的进程有不同的端口号
- 范围:被规定为一个16位的整数 0~65535
-
端口号与IP地址的组合得出一个网络套接字:Socket
端口号

网络协议

- 三次握手:建立连接
- 四次挥手:释放连接
TCP网络编程例题
网络编程例题一
-
客户端
- 创建Socket对象,指明服务器端的ip和端口号
- 获取一个输出流,用于输出数据
- 写出数据
- 关闭资源
-
服务器端
- 创建服务器端的ServerSocket,指明自己的端口号
- 调用accept()方法,表示接收来自于客户端的socket
- 获取输入流
- 读取输入流的数据
- 关闭资源
package com.zzb.Socket;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPTest {
//客户端
@Test
public void client() {
Socket socket = null;
OutputStream os = null;
try {
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet, 8890);
os = socket.getOutputStream();
os.write("你好,我是客户端".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//服务端
@Test
public void sever() {
ServerSocket serverSocket = null;
Socket accept = null;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
serverSocket = new ServerSocket(8890);
accept = serverSocket.accept();
inputStream = accept.getInputStream();
//不建议这样写,可能会有乱码
// byte[] bytes = new byte[1024];
// int length;
// while ((length = inputStream.read(bytes)) != -1) {
// String str = new String(bytes, 0, length);
// System.out.println(str);
// }
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[10];
int length;
while ((length = inputStream.read(bytes)) != -1) {
byteArrayOutputStream.write(bytes, 0, length);
}
System.out.println(byteArrayOutputStream);
System.out.println("收到的数据来自于:" + accept.getInetAddress().getHostAddress());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (accept != null) {
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
网络编程例题二
网络编程例题三
Tomcat服务器
- 看B站javaweb
UDP网络编程
URL编程

- URL网络编程
- URL:统一资源定位符,对应着互联网的某一资源地址
- 格式:
http://localhost:8080/example/beauty.jpg?username=Tom
协议 主机名 端口号 资源地址 参数列表
本文介绍网络编程的基础概念,包括IP地址和端口号的作用,TCP/IP协议的理解与运用,并通过实例展示了客户端与服务器端的交互过程。
3万+

被折叠的 条评论
为什么被折叠?



