网络编程基础
网络编程
1.1概述
信件📃
packet:对方的信息,对方的名称,对方的地址,自己的地址
打电话: --连接--接听--通话-- TCP
发短信:--发送了就完事--接收-- UDP
计算机网络
计算机网络系统就是利用通信设备和线路将地理位置不同、功能独立的多个计算机系统互联起来,以功能完善的网络软件实现网络中资源共享和信息传递的系统。通过计算机的互联,实现计算机之间的通信,从而实现计算机系统之间的信息、软件和设备资源的共享以及协同工作等功能,其本质特征在于提供计算机之间的各类资源的高度共享,实现便捷地交流信息和交换思想。
网络编程的目的:
传播交流信息
想要达到的效果
1.准确定位网络上的一台主机 192.168.16.124 : port,定位到计算机上的某个资源
2.找到这个主机,如何传输数据
Javaweb 网页编程 B/S
网络编程: TCP/IP C/S
1.2网络通信的要素
如何实现网络通信?
通信双方地址
-
IP
-
端口号

规则:网络通讯协议
1.3 IP
ip地址: InetAddress
-
唯一定位一台网络上的计算机
-
127.0.0.1:本机
-
ip分类
-
公网-私网
-
ipv4/ipv6
-
-
域名
//测试IP
public class Test {
public static void main(String[] args) {
try {
//查询本机地址
InetAddress address1 = InetAddress.getByName("127.0.0.1");
System.out.println(address1);
InetAddress address2 = InetAddress.getByName("localhost");
System.out.println(address2);
InetAddress address3 = InetAddress.getLocalHost();
System.out.println(address3);
//查询网站地址
InetAddress address4 = InetAddress.getByName("www.baidu.com");
System.out.println(address4);
//常用方法
System.out.println(address4.getAddress());
System.out.println(address4.getCanonicalHostName());
System.out.println(address4.getHostAddress());
System.out.println(address4.getHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
1.4端口
端口表示计算机上的一个程序的进程;
-
不同的进程有不同的端口号!用来区分软件
-
被规定0~65535
-
TCP,UDP:65535*2
-
端口分类
-
共用端口 0~1023
- HTTP:80
- HTTPs:443
- FTP: 21
- Telent: 23
-
程序注册端口:1024~49151
- Tomcat:8080
- MySql :3306
-
动态,私有端口:49152~65535
-
public class TestInetSocketAdderss {
public static void main(String[] args) {
InetSocketAddress socketAddress1 = new InetSocketAddress("127.0.0.1",8080);
InetSocketAddress socketAddress2 = new InetSocketAddress("localhost",8080);
System.out.println(socketAddress1);
System.out.println(socketAddress2);
System.out.println(socketAddress1.getAddress());
System.out.println(socketAddress1.getHostName());
System.out.println(socketAddress1.getHostString());
System.out.println(socketAddress1.getPort());
}
1.5 通讯协议
重要:
-
TCP:用户传输协议
-
打电话
- 连接,稳定
- 三次握手,四次挥手
三次握手:至少需要三次,保持稳定连接 A:你瞅啥? B:瞅你咋地? A:干一场! A:我要走了! B:你真的要走了吗? A:你真的真的要走了吗? A:我真的要走了!- 客户端,服务端
- 传输完成,释放连接
-
-
UDP:用户数据报协议
- 发短信
- 不连接,不稳定
- 不管有没有准备好,都可以发给你
- 洪泛传播
- 发短信
1.6 TCP
客户端
1.连接服务器socket
2.发送消息
服务器
1.建立服务端口ServerSocket
2.等待用户连接accept
3.接收用户消息
数据传输
客户端代码
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
//客户端
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
//1.知道服务器的地址
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
//2.端口号
int port = 9999;
//3.创建一个socket连接
socket = new Socket(serverIP,port);
//4.IO流 发送消息
os = socket.getOutputStream();
os.write("好好学习".getBytes());
} catch (Exception 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();
}
}
}
}
}
服务端代码
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务端
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1.我得有一个地址
serverSocket = new ServerSocket(9999);
while (true) {
//等到客户端连接过来
socket = serverSocket.accept();
//读取客户端的消息
is = socket.getInputStream();
//管道流
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
System.out.println(baos.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
文件上传
客户端
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientDemo02 {
public static void main(String[] args) throws Exception {
//创建socket连接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9998);
//创建一个输出流
OutputStream os = socket.getOutputStream();
//文件流,读取文件
FileInputStream fis = new FileInputStream(new File("NatureCao.txt"));
//写出文件
byte[] buffer = new byte[1024];
int len;
while ((len=fis.read(buffer))!=-1){
os.write(buffer,0,len);
}
//通知服务器,出书完成
socket.shutdownOutput();
//确定服务端接收完毕
InputStream is = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
while((len2=is.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
baos.close();
is.close();
fis.close();
os.close();
socket.close();
}
}
服务器
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo02 {
public static void main(String[] args) throws Exception {
//创建服务
ServerSocket serverSocket = new ServerSocket(9998);
//监听客户端连接
Socket socket = serverSocket.accept();
//获取输入流
InputStream is = socket.getInputStream();
//文件输出
FileOutputStream fos = new FileOutputStream("receive.txt");
byte[] buffer = new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
//通知客户端接收完毕
OutputStream os = socket.getOutputStream();
os.write("接收完毕".getBytes());
os.close();
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
1.7 UDP
发短信,需要知道对方的地址
发送端
public class UdpClientDemo01 {
public static void main(String[] args) throws Exception {
//建立一个socket
DatagramSocket socket = new DatagramSocket();
String msg = "hello";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9090;
//建立一个包
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
//发送包
socket.send(packet);
socket.close();
}
}
接收端
public class UdpServerDemo01 {
public static void main(String[] args) throws Exception {
//开放端口
DatagramSocket socket = new DatagramSocket(9090);
//接收数据包
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
socket.close();
}
}
两个人聊天:
首先实现循环发送接收
发送者
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class UdpSenderDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8888);
//准备数据,控制台读取System.in
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true){
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));
socket.send(packet);
if (data.equals("bye"))
break;
}
socket.close();
}
}
接收者
package com.miar.chat;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceiverDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666);
while(true){
//准备接受数据包
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
socket.receive(packet); //阻塞式接收
//断开连接
byte[] data = packet.getData();
String receiveData = new String(data,0,data.length);
System.out.println(receiveData);
if (receiveData.equals("bye")){
break;
}
}
// socket.send();
socket.close();
}
}
再实现两个人相互发送接收:多线程
实现Runnable接口
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class TalkSend implements Runnable{
DatagramSocket socket = null;
BufferedReader reader = null;
private int fromPort;
private String toIP;
private int toPort;
public TalkSend(int fromPort, String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try {
socket = new DatagramSocket(fromPort);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
String data = null;
try {
data = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort));
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
if (data.equals("bye"))
break;
}
socket.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReceive implements Runnable{
DatagramSocket socket = null;
private int Port;
private String msgFrom;
public TalkReceive(int port,String msgFrom) {
this.Port = port;
this.msgFrom = msgFrom;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true){
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = packet.getData();
String receiveData = new String(data,0,data.length);
System.out.println(msgFrom+":"+receiveData);
if (receiveData.equals("bye")){
break;
}
}
socket.close();
}
}
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkSend(5555,"localhost",8888)).start();
new Thread(new TalkReceive(9999,"学生")).start();
}
}
public class TalkStudent {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TalkReceive(8888,"老师")).start();
}
}
1.8 URL
统一资源定位符:定位互联网上的某一个资源
协议://ip地址:端口/项目名/资源

浙公网安备 33010602011771号