概述
地球村
什么是计算机网络?
计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统
网络编程的目的:
无限电台…传播交流信息,数据交换,通信
网络通信的要素
1.地址
2.协议
小结:
-
网络编程中有两个主要的问题
- 如何准确的定位到网络上的一台或者多台主机
- 找到主机之后如何进行通信
-
网络编程中的要素
- IP 和 端口号 IP
- 网络通信协议 udp,tcp
-
万物皆对象
IP和网络通信协议都可以生成对象
先看下IP
ip地址:对应java类 InetAddress
唯一定位一台网络上计算机 127.0.0.1:本机Iocalhost
ip地址的分类
ipv4/ipv6
- IPV4:127.0.01 ,4个字节组成,0~255,总共42亿;30亿都在北美,亚洲4亿,2011年就已经用尽,一个字节是一个字母或者数字 ,一个字符是两个字节
- IPV6:128位。8个无符号整数。2001:acca:0ac1:0002:0ab7:1153:2210:ccc1 一个字节=8bit=8位 1个十六进制占4位(bit)
公网(互联网)-私网(局域网)
public static void main(String[] args) {// TODO Auto-generated method stub
try {
//查询本机地址
InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress1);
InetAddress inetAddress3 = InetAddress.getByName("localhost");
System.out.println(inetAddress3);
InetAddress inetAddress4 = InetAddress.getLocalHost();
System.out.println(inetAddress4);
//查询网站ip地址
InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress2);
//常用方法
System.out.println(Arrays.toString(inetAddress2.getAddress())); //返回一个数组
System.out.println(inetAddress2.getCanonicalHostName()); //规范的名字
System.out.println(inetAddress2.getHostAddress()); //ip
System.out.println(inetAddress2.getHostName()); //域名,或者自己电脑的名字
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
端口
端口表示计算机上的一个程序的进程
-
不同的进程有不同的端口!用来区分软件!
-
被规定0~65535,不能使用相同的端口
-
TCP,UDP:65535*2,tcp : 80, udp : 80 这样不影响。单个协议下,端口号不能冲突
-
端口分类
公有端口 0~1023 (尽量不用) HTTP:80 ;HTTPs:443 ;FTP:21 ; Telent:23
程序注册端口:1024~49151,分配用户或者程序 tomcat:8080;mysql:3306;oracle:1527
动态、私有:49152~65535(尽量不用) idea的html:63342
netstat -ano #查看所有的端口
netstat -ano|findstr "5900" #查看指定的端口
tasklist|findstr "8696" #根据pid查看指定端口的进程
InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8080);
InetSocketAddress socketAddress2 = new InetSocketAddress("localhost",8080);
System.out.println(socketAddress);
System.out.println(socketAddress2);
通信协议
网络通信协议:速率、传输码率、代码结构、传输控制… …
主要使用:TCP/IP协议簇:实际上是一组协议
- TCP:用户传输协议 {类似于打电话,需要两边进行连接}
- UDP:用户数据报协议 {类似于发短信,不需要两边连接也可以发出,但不一定能送到
三次握手四次挥手
a关闭发送 b关闭接收 b关闭发送 a关闭接收
所谓套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制。从所处的地位来讲,套接字上联应用进程,下联网络协议栈,是应用程序通过网络协议进行通信的接口,是应用程序与网络协议根进行交互的接口。
Socket是由IP地址和端口结合的,提供向应用层进程传送数据包的机制
客户端发送请求
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
//客户端
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");
int port = 9999;
System.out.println("客户端连接成功");
//2.创建一个 socket 连接
socket = new Socket(serverIP,port);
//3.发送消息 IO 流
os = socket.getOutputStream();
os.write("你好,欢迎学习狂神说Java".getBytes());
System.out.println("已发送");
} catch (IOException e) {
e.printStackTrace();
}
//保证代码的严谨性
if (socket!= null){try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}}
if (os!=null){try {
os.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);
int i = 0;
while (true){
//2.等待客户端连接过来
System.out.println("等待客户端连接");
socket = serverSocket.accept();
//3.读取客户端的信息
i++;
is =socket.getInputStream();
System.out.println("读取信息成功"+i);
baos = new ByteArrayOutputStream();
//创建一个接收数据的byte[]数组,及数组的有效长度len
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
}
}
/*//一种方法
//创建一个接收数据的byte[]数组,及数组的有效长度len
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer))!=-1){
String msg = new String(buffer,0,len);
System.out.println(msg);
}*/
//管道流获得信息
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();
}
}
}
}
}
TCP实现文件上传
package com.test;
import com.sun.deploy.util.SessionState;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TestClientSocket2 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = null;
Socket socket = null;
OutputStream outputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
InputStream inputStream = null;
try {
fileInputStream = new FileInputStream(new File("D:\\ideaWordspace\\text-thread\\thread\\8b.jpg"));
socket = new Socket(InetAddress.getByName("127.0.0.1"), 1111);
outputStream = socket.getOutputStream();
byte[] bytes = new byte[1024];
int len=0;
while ((len=fileInputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
socket.shutdownOutput();
inputStream = socket.getInputStream();
byteArrayOutputStream = new ByteArrayOutputStream();
while ((len=inputStream.read(bytes))!=-1){
byteArrayOutputStream.write(bytes,0,len);
}
System.out.println(byteArrayOutputStream);
} 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(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.test;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServerSocket2 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
Socket accept = null;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
OutputStream outputStream = null;
try {
serverSocket = new ServerSocket(1111);
accept = serverSocket.accept();
inputStream = accept.getInputStream();
fileOutputStream = new FileOutputStream(new File("8b1.jpg"));
byte[] bytes = new byte[1024];
int len=0;
while ((len=inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);
}
outputStream = accept.getOutputStream();
outputStream.write("服务端收到图片啦!".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fileOutputStream != null){
try {
fileOutputStream.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();
}
}
}
}
}
UDP消息发送
package com.test.udp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class TestChatter {
}
class Chatter{
InetAddress ip;
int sayPort;
int listenPort;
int toPort;
public Chatter(String ip,int sayPort,int listenPort,int toPort) throws UnknownHostException {
this.ip = InetAddress.getByName(ip);
this.sayPort=sayPort;
this.toPort=toPort;
this.listenPort=listenPort;
}
public void say() throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(sayPort);
while (true){
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String msg = bufferedReader.readLine();
//System.out.println("好友"+Thread.currentThread().getName()+"说:"+msg);
byte[] msgs = msg.getBytes();
DatagramPacket datagramPacket = new DatagramPacket(msgs,0,msgs.length,ip,toPort);
datagramSocket.send(datagramPacket);
if("bye".equals(msg)){
break;
}
}
datagramSocket.close();
System.out.println(Thread.currentThread().getName()+"end");
}
public void listen() throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(listenPort);
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length);
while (true){
datagramSocket.receive(datagramPacket);
byte[] data = datagramPacket.getData();
String receiveMsg =new String(data, 0, datagramPacket.getLength());
System.out.println("好友"+datagramPacket.getSocketAddress()+"说:"+receiveMsg);
if("bye".equals(receiveMsg)){
break;
}
}
datagramSocket.close();
System.out.println(Thread.currentThread().getName()+"end");
}
}
package com.test.udp;
import java.io.IOException;
import java.net.UnknownHostException;
public class TestReceiverChat {
public static void main(String[] args) throws UnknownHostException {
Chatter chatter = new Chatter("127.0.0.1",1600,1601,1501 );
new Thread(()->{
try {
chatter.say();
} catch (IOException e) {
e.printStackTrace();
}
},"聊天者B说话线程").start();
new Thread(()->{
try {
chatter.listen();
} catch (IOException e) {
e.printStackTrace();
}
},"聊天者B倾听线程").start();
}
}
package com.test.udp;
import java.io.IOException;
import java.net.UnknownHostException;
public class TestSenderChat {
public static void main(String[] args) throws UnknownHostException {
Chatter chatter = new Chatter("127.0.0.1",1500,1501,1601);
new Thread(()->{
try {
chatter.say();
} catch (IOException e) {
e.printStackTrace();
}
},"聊天者A说话线程").start();
new Thread(()->{
try {
chatter.listen();
} catch (IOException e) {
e.printStackTrace();
}
},"聊天者A倾听线程").start();
}
}