计算机网络编程---学习笔记

网络编程的目的:数据交换,网络通信。

网络通信的要素

通信双方的地址:

·ip

·端口号

规则:网络通信协议

TCP/IP UDP

 IP

ip地址:InetAddress

·唯一定位一台网络计算机

·127.0.0.1 本机 localhost

·ip地址的分类

        ·IP地址分类:IPV4/IPV6

                ·IPV4 127.0.0.1 4个字节组成  0~255 42亿  30在北美 亚洲4亿  2011年用尽;

                ·IPV6  fe80::5c07:f301:db6f:7231%13 128位 8个无符号整数

        ·公网地址 私网地址 

端口

端口表示计算机上的一个程序的进程;

        不同的进程有不同的端口号!用来区分软件!

        被规定0~65535

        TCP,UDP:65535*2 单个协议下端口不能冲突

        端口分类

                公有端口 0~1023

                        HTTP:80端口

                        HTTP:443端口

                        FTP:21

                        Telent:23

                程序注册端口:1024~49151,分配给用户给程序

                        Tomcat:8080

                        MySQL:3306

                        Oracle:1521

                动态、私有端口:49152~65535

                        netstat -ano 查看所有端口

                        netstat -ano|findstr  "5900" #查看指定端口

                        tasklist | findstr " " 查看某个特定的进程

通信协议 

协议:约定。

网络通信协议:速率,传输码率,代码结构,传输控制......

TCP/IP协议簇

        TCP:用户传输协议

        UDP:用户数据报协议

出名的协议:

        TCP:

        IP:网络互联协议

        一个协议

TCP UDP对比

TCP:连接,稳定 

        三次握手 四次挥手

     最少需要三次,保证稳定连接

         A:你瞅啥

        B:瞅你咋地

        A:打一架

        

四次挥手

        A:我要断开了

        B:你真的断开了?

        B:你真的真的要断开了?

        A:我真的要断开了!

        客户端 和 服务端 

        传输完成,释放连接 效率低

UDP:不连接,不稳定

        客户端和服务端:没有明确的界限

        不管咋样都会发送给你

        DDOS(饱和攻击)

TCP

客户端

1.连接服务器Socket

2.发送消息

//客户端
public class TcpClientDemo1 {
	public static void main(String[] args) {
		InetAddress serverIP =null;
		Socket socket =null;
		OutputStream os =null;
		//要知道服务器地址
		try {
			serverIP = InetAddress.getByName("127.0.0.1");
			int port= 9999;
			//创建一个socket连接
			socket = new Socket(serverIP,port);
			//发送消息 IO流
			 os = socket.getOutputStream();
			os.write("你好 学java".getBytes());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(os!=null) {
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			if(socket!=null) {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
}

服务器

1.建立服务的端口 ServerScocket

2.等待用户的链接 accept

3.接受用的消息

//服务端
public class TcpServerDemo1 {
	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		Socket socket = null;
		InputStream is =null;
		ByteArrayOutputStream baos = null;
		try {
			//我得有一个地址
			serverSocket = new ServerSocket(9999);
			//等待客户端连接
			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) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(baos!=null) {
				try {
					baos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			if(is!=null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(socket!=null) {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(serverSocket!=null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			
		}
	}
}

文件上传

//服务端接受文件	
public class TcpServerDemo2 {
	public static void main(String[] args) throws Exception {
		//创建一个服务
		ServerSocket serverSocket = new ServerSocket(9000);
		//监听客户端的连接
		Socket socket = serverSocket.accept();//阻塞式监听 会一直等待客户端连接
		//获取输入流
		InputStream inputStream = socket.getInputStream();
		
		//文件输出
		FileOutputStream fos = new FileOutputStream(new File("123.txt"));
		byte[] buffer = new byte[1024];
		int len;
		while((len=inputStream.read(buffer))!=-1) {
			fos.write(buffer,0,len);
		}
		//通知客户端接受完毕
		OutputStream os = socket.getOutputStream();
		os.write("接受完毕".getBytes());
		//关闭资源
		fos.close();
		inputStream.close();
		socket.close();
		serverSocket.close();
	}

}
//客户端上传文件
public class TcpClientDemo2 {
	public static void main(String[] args) throws Exception{
		//创建一个Socket连接
		Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
		//创建一个输出流
		OutputStream os = socket.getOutputStream();
		
		//读取文件
		FileInputStream fis = new FileInputStream(new File("git.txt"));
		//写出文件
		byte[] buffer = new byte[1024];
		int len;
		while((len=fis.read(buffer))!=-1) {
			os.write(buffer,0,len);
		}
		
		//通知服务器 已经结束
		socket.shutdownOutput();//已经传输完了
		//确定服务器接受完毕才能断开
		InputStream inputStream = socket.getInputStream();
		
		ByteArrayOutputStream baso = new ByteArrayOutputStream();
		byte[] buffer2 = new byte[1024];
		int len2;
		while((len2=inputStream.read(buffer2))!=-1) {
			baso.write(buffer2,0,len2);
		}
		
		System.out.println(baso.toString());
		//关闭资源
		baso.close();
		inputStream.close();
		fis.close();
		os.close();
		socket.close();
	}

}

Tomcat

服务器 Java后台开发

UDP

不需要连接 知道对方的地址

//不需要连接服务器
public class UdpClientDemo1 {
	public static void main(String[] args) throws Exception {
		//建立一个Socket
		DatagramSocket socket = new DatagramSocket();
		
		//建个包
		String msg = "你好啊 服务器";
		
		
		//发给谁
		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 UdpSenderDemo1 {
	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 s = reader.readLine();
		byte[] date = s.getBytes();
		DatagramPacket packet = new DatagramPacket(date, 0,date.length,new InetSocketAddress("localhost",6666));
		
		socket.send(packet);
		if(date.toString().equals("bye")) {
			break;
		}
		}
		socket.close();
	}

}
//接收
public class UdpReceiveDemo1 {
	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.toString().equals("bye")) {
			break;
		}
		}	
		socket.close();
		
		
		
	}

}

交互发送 即是发送方 也是接受方

//发送
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) {
		// TODO Auto-generated constructor stub
		this.fromPort = fromPort;
		this.toIP = toIP;
		this.toPort = toPort;
		try {
			socket = new DatagramSocket(fromPort);
			//准备数据 控制台读取System.in
			reader = new BufferedReader(new InputStreamReader(System.in));
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		
		while(true) {
			try {
				String s = reader.readLine();
				byte[] date = s.getBytes();
				DatagramPacket packet = new DatagramPacket(date, 0,date.length,new InetSocketAddress(this.toIP,this.toPort));
				socket.send(packet);
				if(date.toString().equals("bye")) {
					break;
				}
			
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		socket.close();
		
	}
	

}
//接收
public class TalkReceive implements Runnable{
	DatagramSocket socket =null;
	
	private int Port;
	private String msg;
	
	
	public TalkReceive(int Port,String msg) {
		this.Port = Port;
		this.msg = msg;
		
		try {
			socket = new DatagramSocket(Port);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	@Override
	public void run() {
		// TODO Auto-generated method stub
		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(msg+":"+receiveData);
				if(receiveData.toString().equals("bye")) {
					break;
				}
			
				
			}catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		socket.close();
			
	}	
		
		

}

url

统一资源定位符:定位资源

DNS域名解析 把域名解析成IP地址


协议://IP地址:端口号/项目名/资源

public static void main(String[] args) throws Exception {
		//下载地址
		URL url = new URL("https://www.baidu.com/");
		
		//连接资源 http
		HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
		
		InputStream inputStream = urlConnection.getInputStream();
		
		FileOutputStream fos = new FileOutputStream(new File("baidu.txt"));
		byte[] buffer = new byte[1024];
		int len;
		while((len=inputStream.read(buffer))!=-1) {
			fos.write(buffer,0,len);
		}
		
		fos.close();
		inputStream.close();
		urlConnection.disconnect();
	}

上一篇:Android Studio进行Socket通信


下一篇:python mysql应用