Java 网络编程
1、概述
**计算机网络:**计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统、网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。
**网络编程的目的:**传播交流信息,数据交换,通信。
**达到这个效果需要什么:**1、如何准确定位网络上的一台主机,IP+端口;端口定位到这个计算机上的某个资源。
2、找到主机,如何传输数据;TCP/IP C/S B/S
2、网络通信的要素
通信双方的地址:
- IP
- 端口号
规则,网络通信协议:
http,ftp,smtp,tcp,udp(OSI七层参考协议)
3、IP
IP地址:InetAddress类
-
唯一定位一台计算机
-
127.0.0.1表示本机(localhost)
-
IP地址分类:
-
IPV4/IPV6和公网/私网
-
IPV4由四个字节组成,0~255,42亿个(数量不够,2011年耗尽)
-
IPV6:128位,8个无符号整数110,ae
-
公网(互联网)ABCD类地址
-
私网(局域网)如192.168.XXX.XXX
-
-
域名:记忆IP问题
import java.net.InetAddress;
import java.net.UnknownHostException;
//测试IP
public class TestInetAddress {
public static void main(String[] args) {
try {
//查询本机地址
System.out.println(InetAddress.getByName("127.0.0.1"));
System.out.println(InetAddress.getByName("localhost"));
System.out.println(InetAddress.getLocalHost());
//查询网站地址
InetAddress inetAddress=InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress);
//常用方法
System.out.println(inetAddress.getAddress());
System.out.println(inetAddress.getCanonicalHostName());//获得规范IP
System.out.println(inetAddress.getHostName());//获得主机域名
System.out.println(inetAddress.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
4、端口
一个端口对应一个进程。
- 不同的进程有不同的端口号,不可冲突
- 端口被规定为0~65535,故TCP/UDP=65535*2个端口
- 端口分类
- 公有端口 0~1023内置进程使用
- HTTP:80
- HTTPS:443
- FTP:21
- Telnet:23
- 程序注册端口1024~49151
- Tomcat:8080
- MySQL:3306
- Oracle:1521
- 动态、私有端口 49152~65535
- 公有端口 0~1023内置进程使用
netstat -ano #查看所有端口
netstat -ano|findstr="5900" #查看给定端口
tasklist|findstr "8696" #查看指定端口对应的进程
InetSocketAddress类(与InetAddress类似,增加端口,区别是有构造函数)
5、通信协议
网络通信协议:速率、传输码率、代码结构、传输控制…
TCP/IP协议簇:
TCP(用户传输协议)
- 连接,稳定
- 三次握手四次挥手
- 客户端、服务端
- 传输完成,释放连接
UDP(用户数据报协议)
- 不连接,不稳定
- 客户端服务器没有明确界限
- 不需准备好
IP(网络互联协议)
6、TCP
客户端
- 连接服务器Socket
- 发送消息
服务器端
- 建立服务端口ServerSocket
- 等待用户连接accept
- 接收用户消息
例:客户端传字符串至服务器端
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TestTCPClient {
public static void main(String[] args) throws IOException {
Socket socket=null;
OutputStream ops=null;
try {
InetAddress serverIP=InetAddress.getByName("127.0.0.1");
int port=9999;//端口号
try {
//创建Socket连接
socket=new Socket(serverIP,port);
//发送消息IO流
ops=socket.getOutputStream();
ops.write("Hello Socket".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
}finally {
if(ops!=null){
ops.close();
}
if(socket!=null){
socket.close();
}
}
}
}
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TestTCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=null;
Socket socket=null;
InputStream ips=null;
ByteArrayOutputStream baos=null;
try {
serverSocket=new ServerSocket(9999);
socket=serverSocket.accept();
ips=socket.getInputStream();
baos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len;
while((len=ips.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if(baos!=null){
baos.close();
}
if(ips!=null){
ips.close();
}
if(socket!=null){
socket.close();
}
if(serverSocket!=null){
serverSocket.close();
}
}
}
}
例:文件上传:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TestTCPPicServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=new ServerSocket(9000);//创建服务
Socket socket=serverSocket.accept();
InputStream ips=socket.getInputStream();//输入流
FileOutputStream fos=new FileOutputStream(new File("receive.jpg"));//输出流
byte[] buffer=new byte[1024];
int len;
while((len=ips.read(buffer))!=-1){
fos.write(buffer,0,len);
}
fos.close();
ips.close();
socket.close();
serverSocket.close();
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class TestTCPPicClient {
public static void main(String[] args) throws IOException {
Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9000);//创建链接
OutputStream ops=socket.getOutputStream();//创建输出流
FileInputStream fis=new FileInputStream(new File("C:\\Users\\pierc\\Pictures\\证件\\1554450372139.jpg"));//文件流
//写文件
byte[] buffer=new byte[1024];
int len;
while ((len=fis.read(buffer))!=-1){
ops.write(buffer,0,len);
}
fis.close();
ops.close();
socket.close();
}
}
7、Tomcat
服务端
- 自定义
- Tomcat服务器
客户端
- 自定义Client
- Tomcat Browser
8、UDP
DatagramPacket 该类表示数据报包
DatagramSocket 接收数据报包
8.1、UDP传输字符串
import java.io.IOException;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class TestUDPServer {
public static void main(String[] args) throws IOException {
//开放端口
DatagramSocket datagramSocket=new DatagramSocket(9090);
//接收数据
byte[] buffer=new byte[1024];
DatagramPacket datagramPacket=new DatagramPacket(buffer,0,buffer.length);
datagramSocket.receive(datagramPacket);
System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
datagramSocket.close();
}
}
import java.io.IOException;
import java.net.*;
public class TestUDPClient {
public static void main(String[] args) throws IOException {
//建立socket
DatagramSocket datagramSocket=new DatagramSocket();
//发给谁
InetAddress localhost=InetAddress.getByName("127.0.0.1");
int port=9090;
//建包
String message="Hello UDP";
DatagramPacket datagramPacket=new DatagramPacket(message.getBytes(),0,message.getBytes().length,localhost,port);
//发送包
datagramSocket.send(datagramPacket);
//关闭流
datagramSocket.close();
}
}
8.2、UDP聊天
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 TestChatSend implements Runnable{
private DatagramSocket datagramSocket=null;
private BufferedReader br=null;
private int fromPort;
private String toIP;
private int toPort;
public TestChatSend(int fromPort, String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try {
datagramSocket=new DatagramSocket(fromPort);
br=new BufferedReader(new InputStreamReader(System.in));
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try{
String data= br.readLine();
byte[] datas=data.getBytes();
DatagramPacket datagramPacket=new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));
datagramSocket.send(datagramPacket);
if(new String(datas,0,datas.length).equals("bye")){
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
datagramSocket.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TestChatReceive implements Runnable{
private DatagramSocket datagramSocket=null;
private int port;
private String actor;
public TestChatReceive(int port,String actor) throws SocketException {
this.port = port;
this.actor=actor;
datagramSocket=new DatagramSocket(port);
}
@Override
public void run() {
while (true){
byte[] container=new byte[1024];
DatagramPacket datagramPacket=new DatagramPacket(container,0,container.length);
try {
datagramSocket.receive(datagramPacket);
} catch (IOException e) {
e.printStackTrace();
}
byte[] data=datagramPacket.getData();
String receiveData=new String(data,0,datagramPacket.getLength());
System.out.println(actor+"发来的:"+receiveData);
if(receiveData.equals("bye")){
break;
}
}
datagramSocket.close();
}
}
import java.net.SocketException;
public class TestChatStudent {
public static void main(String[] args) throws SocketException {
new Thread(new TestChatSend(7777,"localhost",9999)).start();
new Thread(new TestChatReceive(8888,"老师")).start();
}
}
import java.net.SocketException;
public class TestChatTeacher {
public static void main(String[] args) throws SocketException {
new Thread(new TestChatSend(5555,"localhost",8888)).start();
new Thread(new TestChatReceive(9999,"学生")).start();
}
}