网络编程
1.1概述
计算机网络
计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接(有线、无线)起来,在网络操作系统,网络管理软件及**网络通信协议**的管理和协调下,实现资源共享和信息传递的计算机系统。
网络编程的目的:
无线电台。。。 传播交流信息、数据交换、通信
想要达到这个效果需要什么
1.如何准确地定位网络上的一台主机? 192.168.1.1: 端口,定位到这个计算机上的某个资源
2.找到了这个主机,如何传输数据呢?
网络编程:TCP/IP C/S架构
1.2网络通行的要素
如何实现网络通信?
通信双方的地址:
- ip
- 端口号
- 192.168.16.124:5900
规则:网络通信的协议
小结:
1.网络编程中有两个主要问题
- 如何准确地定位到网络上的一台或者多台主机
- 找到主机之后如何进行通信
2.网络编程中的要素
- IP和端口号 IP
- 网络通信写协议 UDP、TCP
3.万物皆对象
1.3 IP
ip地址:InetAddress
-
唯一定位一台网络上计算机
-
127.0.0.1:本机localhost
-
IP地址的分类
-
ipv4 /ipv6
-
ipv4:127.0.0.1 4个字节组成, 0~255,42 亿~ ;30亿都在北美,亚洲4亿。2011年就用尽;
-
ipv6:fe80::1d96:105:f5a:7792%7 , 128位。8个无符号整数!
-
-
2001:0bb2:aaaa:0015:0000:0000:1aaa:1312
公网(互联网)—私网(局域网)
ABCD类地址
192.168.xx.xx 专门给组织内部使用的
- 域名:记忆IP问题!
- Ip : www.vip.com
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TestInetAddress {
public static void main(String[] args) throws Exception {
//查询本机的ip地址
InetAddress localhost = InetAddress.getByName("localhost");
System.out.println(localhost);
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost);
System.out.println("=================");
//查询网站ip地址
InetAddress name = InetAddress.getByName("www.baidu.com");
System.out.println(name);
System.out.println("=================");
//常用方法
//System.out.println(name.getAddress());
System.out.println(name.getHostAddress());//获取主机ip地址
System.out.println(name.getHostName());// 获取域名
System.out.println(name.getCanonicalHostName());//获取规范的主机ip地址
}
}
1.4 端口
端口表示计算机上的一个程序的进程。
-
不同的进程有不同的端口号。 用来区分软件。
-
被规定0~65535
-
TCP,UDP :65535*2 tcp:80 ,dup:80 ,单个协议下,端口号不能冲突
-
端口分类
-
公有端口0~1023
-
HTTP:80
-
HTTPS:443
-
FTP:21
-
Telent:23
-
-
程序注册端口:1014~49151 ,分配用户或程序
- Tomcat:8080
- MySQL:3306
- Oracle:1521
-
动态、私有:49152~65535
dos命令:
netstat -ano #查看所有端口 netstat -ano | findstr "5900" #查看指定的端口 tasklist | findstr "8696" #查看指定端口的进程
-
练习代码:
import java.net.InetSocketAddress;
public class TesyInetSocketAddress {
public static void main(String[] args) {
InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8080);
InetSocketAddress socketAddress1 = new InetSocketAddress("localhost", 8080);
System.out.println(socketAddress);
System.out.println(socketAddress1);
System.out.println("====================");
System.out.println(socketAddress.getAddress());//ip地址
System.out.println(socketAddress.getHostName());//主机名称
System.out.println(socketAddress.getHostString());
System.out.println(socketAddress.getPort());//端口
}
}
1.5通信协议
协议:约定,就好比我们现在说的是普通话。
网络通信协议:速率,传输码率,代码结构,传输控制。。。。
问题:非常的复杂?
大事化小:分层!
TCP/IP协议:实际上是一组协议
重要:
- TCP:用户传输协议
- UDP:用户数据报协议
出名的协议:
- TCP:用户传输协议
- IP:网络互连协议
TCP UDP对比
TCP:打电话
- 连接,稳定
- 二次握手,四次挥手
最少需要三次,保证稳定链接
aba abba
- 客户端、服务端
- 传输完成,释放连接,效率低
UDP:发短信
- 不连接,不稳定
- 客户端、服务端:没有明确的界限
- 不管有没有准备好,都可以发给你
- 导弹
- DDOS:洪水攻击 (饱和攻击)
1.6 TCP
客户端:1.要知道服务器地址,端口号
2.创建一个socket连接
3.发送消息 IO流
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDemo1 {
public static void main(String[] args) throws Exception{
Socket socket = null;
OutputStream os = null;
//要知道服务器地址
try {
InetAddress serverIp = InetAddress.getByName("localhost");
int port = 9999;
//2.创建连接
socket = new Socket(serverIp,port);
//3.发生消息 IO流
os = socket.getOutputStream();
os.write("你好,FC".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (os != null) {
os.close();
}
if (socket != null) {
socket.close();
}
}
}
}
服务器:1.我得有一个地址 SeverSocket
2.等待客户端连接过来 accept
3.读取客户端的消息
import java.io.ByteArrayInputStream;
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) throws Exception {
ServerSocket serverSocket = null;
Socket accept = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1. 我得有一个地址
serverSocket = new ServerSocket(9999);
//2.等待客户端连接过来
accept = serverSocket.accept();
//3.读取客户端消息
is = accept.getInputStream();
/*byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) != -1 ){
String s = new String(buf, 0, len);
System.out.println(s);
}*/
//管道流
baos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len;
while ((len = is.read(buff)) != -1) {
baos.write(buff, 0, len);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (baos != null) {
baos.close();
}
if (is != null) {
is.close();
}
if (accept != null) {
accept.close();
}
if (serverSocket != null) {
serverSocket.close();
}
}
}
}
文件上传
服务端
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo2 {
public static void main(String[] args) throws Exception{
//1.创建服务
ServerSocket serverSocket = new ServerSocket(9999);
//2.监听客户端连接
Socket accept = serverSocket.accept();
//3.获取输入流
InputStream is = accept.getInputStream();
//4.文件输出
FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));//接收文件就要用文件的管道流
byte[] buff = new byte[1024];
int len;
while ((len = is.read(buff)) != -1){
fos.write(buff,0,len);
}
//通过客户端我接收完毕了
OutputStream os = accept.getOutputStream();
os.write("我接收完毕了,你可以断开了".getBytes());
fos.close();
is.close();
accept.close();
serverSocket.close();
}
}
客户端
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientDemo2 {
public static void main(String[] args) throws Exception {
//1.建立连接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
//2.创建一个输出流
OutputStream os = socket.getOutputStream();
//3.读取文件
FileInputStream is = new FileInputStream(new File("1.jpg"));
byte[] buff = new byte[1024];
int len;
//4.写出文件
while ((len = is.read(buff)) != -1) {
os.write(buff, 0, len);
}
//通知服务器,我已经结束了
socket.shutdownOutput();//我已经传输完了的意思
//确定服务器接收完毕,才能够断开连接
InputStream inputStream = socket.getInputStream();//接收字符、就用字节的管道流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buff2 = new byte[1024];
int len2;
while ((len2 = inputStream.read(buff)) != -1) {
bos.write(buff2, 0, len2);
}
System.out.println(bos.toString());
//5.释放资源
bos.close();
inputStream.close();
is.close();
os.close();
socket.close();
}
}
1.7 UDP
发短信:不用连接,需要知道对方的地址
发送
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpClientDemo1 {
public static void main(String[] args) throws Exception{
//1.建立一个Socket
DatagramSocket socket = new DatagramSocket();
//2.建个包
String msg = "你好啊,服务器";
//3.发送给谁
InetAddress address = InetAddress.getByName("localhost");
int port = 9090;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, address, port);
//4.发送包
socket.send(packet);
}
}
接收
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
public class UdpServerDemo1 {
public static void main(String[] args) throws Exception{
//开放端口
DatagramSocket socket = new DatagramSocket(9090);
//接收数据包
byte[] buff =new byte[1024];
DatagramPacket packet = new DatagramPacket(buff, 0, buff.length);
socket.receive(packet);//阻塞接收
System.out.println(packet.getAddress());
System.out.println(new String(packet.getData(),0,packet.getData().length));
socket.close();
}
}
UDP 实现聊天实现
发送方
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);
while (true) {
//准备数据
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
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();
}
}
接收方
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceiveDemo01 {
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);
//断开连接 bye
if (receiveData.equals("bye")){
break;
}
}
socket.close();
}
}
UDP多线程在线咨询
TalkSend
import java.io.BufferedReader;
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) {
try {
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket
(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort));
socket.send(packet);
if (data.equals("bye")) {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
TalkReceive
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.MulticastSocket;
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(6666);
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
@Override
public void run() {
while (true) {
try {
//准备接收包裹
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(msgFrom+":"+receiveData);
//断开连接 bye
if (receiveData.equals("bye")){
break;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
socket.close();
}
}
TalkTeacher
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkSend(7777,"localhost",8888)).start();
new Thread(new TalkReceive(9999,"学生")).start();
}
}
TalkStudent
public class TalkStudent {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(5555,"localhost",9999)).start();
new Thread(new TalkReceive(8888,"老师")).start();
}
}