Java Network Programming emphasis must-see

network programming

URL

url: Uniform Resource Locator

Three cornerstones of the Internet: html http url

URL categories:

https://www.baidu.com

String getPath () to get part of the URL path.
String getHost () the URL of the host name, if applicable.
int getPort () This port number of the URL.
String getProtocol () the URL of the protocol name.
String getQuery () Gets the query part of the URL.
String getRef () to get the anchor (also known as the "reference") URL.

//简单爬虫
public class Demo01 {
	public static void main(String[] args) throws IOException {
		URL url=new URL("https://www.taobao.com");
		System.out.println(url);
		System.out.println("协议"+url.getProtocol());
		System.out.println("端口"+url.getPort());
		System.out.println("域名"+url.getHost());
		System.out.println("查询内容"+url.getQuery());
		System.out.println("锚点"+url.getRef());
		//获取一个从url位置到程序的输入流
		InputStream str=url.openStream();
		//读取
		byte[] car=new byte[1024];
		int len=-1;
		while((len=str.read(car))!=-1){
			System.out.println(new String(car,0,len));
		}
	}
}

Transport Layer:

  • tcp: Connection-oriented 3-way handshake low efficiency of security spending large size does not limit
  • udp: non-connection-oriented protocol insecure simple little overhead high efficiency just write just send size limit of not more than 60k

Socket-oriented programming

Transport layer to the application layer to open up the hole for outgoing data

UDP

UDP socket to achieve

  • DatagramPacket: Packaging | datagram packet
  • DatagramPacket (byte [] buf, int offset, int length, SocketAddress address) configured packet length of a packet data transmission packet length specified offset ioffsetto host specified port number.
  • DatagramPacket (byte [] buf, int length) Constructs a DatagramPacket length length of the received packet.
  • DatagramSocket: definition of the transmission or receiver
  • DatagramSocket (int port) Constructs a datagram socket bound to the specified port on the local host.
    DatagramSocket (int port, InetAddress laddr) Creates a datagram socket, bound to the specified local address.
UDP basic process:
The sender
  1. Definition of the transmission side DatagramSocket (int port)
  2. According to the quasi-data
  3. Bale
  4. Transmission void send (DatagramPacket p) sending a datagram from the socket packet.
  5. shut down

Note: the lower the slogan unified agreement can not conflict

public class UDPSend02{
	public static void main(String[] args) throws IOException {
		System.out.println("-------------发送端----------------");
		//1.定义发送端DatagramSocket(int port)
		DatagramSocket client=new DatagramSocket(6666);
		//2.准据数据
		byte[] arr="海贼王-->香克斯".getBytes();
		//3.打包
		DatagramPacket packet=new DatagramPacket(arr, 0, arr.length,new InetSocketAddress("localhost",9999));
		//4.发送
		client.send(packet);
		//5.关闭
		client.close();
	}
}
Receiving end
  1. Defines a receiving end DatagramSocket (int port)
  2. Packing for receiving data
  3. Receiving data receive (DatagramPacket p) receiving datagram packets from the socket.
  4. Processing data byte [] getData () int getLength ()
  5. shut down
public class UDPReceive03 {
	public static void main(String[] args) throws IOException {
		System.out.println("-------------接收端----------------");
		//1.定义接收端 DatagramSocket(int port)
		DatagramSocket server=new DatagramSocket(9999);
		//2.打包用来接收数据
		byte[] arr=new byte[1024*60];
		DatagramPacket packet=new DatagramPacket(arr, arr.length);
		//3.接收数据  receive(DatagramPacket p) 从这个套接字接收数据报包。 
		server.receive(packet);
		//4.处理数据
		byte[] data=packet.getData();
		int len=packet.getLength();
		System.out.println(new String(data,0,len));
		System.out.println(data.length);
		System.out.println(len);
		//5.关闭
		server.close();
	}
}

TCP

tcp basic process:
Client
  • 1. Define client Socket Socket (InetAddress address, int port) to create a stream socket to the specified port number in the specified IP address.
  • 2.io operation InputStream getInputStream () Returns the input stream for this socket.
  • 3. Close
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClient04 {
	public static void main(String[] args) throws UnknownHostException, IOException {
		System.out.println("------我是客户端-------");
		//1.定义客户端
		Socket client=new Socket("127.0.0.1",9999);
		//2.IO操作
		OutputStream os=client.getOutputStream();
		os.write("今天是星期六".getBytes());
		//3.刷出
		os.flush();
		//4.关闭
		os.close();
		client.close();
	}
}
Server
  • 1. Define server-side ServerSocket (int port) Creates a server socket bound to the specified port.
  • 2. Blocking listening accept ()
  • 3.io operation
  • 4. Data processing
  • 5. Close
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer05 {
	public static void main(String[] args) throws IOException {
		System.out.println("------我是服务端-------");
		//1.定义服务端  ServerSocket(int port) 创建一个服务器套接字绑定到指定端口。
		ServerSocket server=new ServerSocket(9999);
		//2.阻塞式监听 accept() 
		Socket socket=server.accept(); 
		System.out.println("一个客户端连接成功了.....");
		//3.io操作
		InputStream is=socket.getInputStream();
		byte[] arr=new byte[1024];
		int len=is.read(arr);
		//4.数据的处理
		System.out.println(new String(arr,0,len));
		//5.关闭
		is.close();
		socket.close();
		server.close();
	}
}

Multi-user login

Server
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
public class LoginServer10 {
	public static void main(String[] args) throws IOException {
		System.out.println("------我是服务端-------");
		//1.定义服务端  
		ServerSocket server=new ServerSocket(9999);
		boolean flag=true;
		while(flag){
			//2.阻塞式监听 accept() 
			Socket socket=server.accept(); 
			System.out.println("一个客户端连接成功了.....");
			//3.io操作
			new Thread(new Channel(socket)).start();
			
		}
		
		server.close(); //死循环后面的代码无法执行
	}
	//静态内部类  管道 对每一个登录的用户执行的流程
	static class Channel implements Runnable{
		Socket socket ;
		InputStream is;
		OutputStream os;
		
		public Channel(Socket socket) {
			this.socket=socket;
			try {
				is = socket.getInputStream();
				os=socket.getOutputStream();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		//读入
		public String read(){
			String str="";
			byte[] arr=new byte[1024];
			try {
				int len=is.read(arr);
				str=new String(arr,0,len);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return str;
		}
		
		//写出
		public void write(String msg){
			try {
				os.write(msg.getBytes());
				os.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void run() {
			
			//4.数据的处理
			String data=read();
			//处理方式2
			String uname="";
			String pwd="";
			String[] str=data.split("&");
			for(String s:str){
				System.out.println(s);
				String[] ss=s.split("=");
				System.out.println(Arrays.toString(ss));;
				if(ss[0].equals("name")){
					uname = ss[1];
				}else if(ss[0].equals("pwd")){
					pwd= ss[1];
				}
			}
			//判断
			if(uname.equals("zhangsan")&&pwd.equals("123")){
				write("登录成功");
			}else{
				write("登录失败");
			}
			close();
			
		}
		//关闭
		public void close(){
			//5.关闭
			try {  //alt+shift+z 一段代码一起添加到一个异常中
				if(os!=null){
					os.close();
				}
				if(is!=null){
					is.close();
				}
				if(socket!=null){
					socket.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
Published 13 original articles · won praise 13 · views 500

Guess you like

Origin blog.csdn.net/Rabbit_white_/article/details/104060925