Java 网络编程
网络编程概述
通过 Ip 和 Port 来通信。
TCP/IP参考模型
- 应用层
- 传输层
- 网络层
- 物理 + 数据链路层
IP地址对应的类:InetAddress
端口号 + ip地址 = 网络套接字:socket
TCP 编程
服务端和客户端通信Demo。
@Test
public void client() throws Exception {
InetAddress ip = InetAddress.getByName("localhost");
Socket socket = new Socket(ip, 9999);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello, it is from client, 这是中文测试".getBytes());
outputStream.close();
socket.close();
}
@Test
public void server() throws Exception {
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
int len; byte[] buf = new byte[5];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = inputStream.read(buf)) != -1)
baos.write(buf, 0, len);
System.out.println(baos.toString());
new CountDownLatch(4).await();
baos.close();
socket.close();
inputStream.close();
serverSocket.close();
}
read方法是阻塞的,需要手动关闭,shutdownInputStream
UDP 编程
@Test
public void client() throws Exception {
DatagramSocket socket = new DatagramSocket();
String str = "hello";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data, 0, data.length, inet, 9999);
socket.send(packet);
socket.close();
}
@Test
public void server() throws Exception {
DatagramSocket socket = new DatagramSocket(9999);
byte[] buf = new byte[100];
DatagramPacket pa = new DatagramPacket(buf, 0, buf.length);
socket.receive(pa);
System.out.println(new String(pa.getData(), 0, pa.getLength()));
socket.close();
}
URL 编程
URL : Uniform Resource Locator
<传输协议>://<主机名>:<端口>/<文件名>