2020/4/29学习笔记day51

java-day51

文章目录

  • java-day51
    • 在线聊天(结合网络/多线程/GUI)
    • UDP
    • URI和URL

在线聊天(结合网络/多线程/GUI)

public class ClientGUITest extends JFrame{
	private static final long serialVersionUID = 1L;
	
	private JPanel northPanel,centerPanel;
	private JLabel nameLabel;
	private JTextField nameTextField;
	private JButton btn;
	
	private JTextArea area;
	private JScrollPane scrollPane;
	
	private JTextField msgTextField;
	
	private Hander hander;
	
	public ClientGUITest() {
		super.setBounds(300, 300, 500, 500);
		super.setResizable(false);
		super.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.initComponent();
		super.setVisible(true);
	}
	
	private void initComponent() {
		
		northPanel  = new JPanel();
		centerPanel = new JPanel();
		
		nameLabel = new JLabel("昵称:");
		nameTextField = new JTextField(10);
		btn = new JButton("连接");
		
		area = new JTextArea();
		scrollPane = new JScrollPane(area);
		
		area.setEditable(false);
		area.setLineWrap(true); //自动换行
		area.setBackground(Color.WHITE);
		
		msgTextField = new JTextField();
		
		
		centerPanel.setLayout(new BorderLayout());
		
		northPanel.add(nameLabel);
		northPanel.add(nameTextField);
		northPanel.add(btn);
		
		centerPanel.add(scrollPane,BorderLayout.CENTER);
		
		super.add(northPanel,BorderLayout.NORTH);
		super.add(centerPanel,BorderLayout.CENTER);
		super.add(msgTextField,BorderLayout.SOUTH);
		
		
		
		btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String name = nameTextField.getText();
				if(name!=null && name.replaceAll(" ", "").length()>0) {
					name = name.replaceAll(" ", "");
					nameTextField.setText(name);
					//连接服务器,发送name值
					hander = new Hander(name);
					hander.start();
				}
			}
		});
		
		
		msgTextField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				int keyCode = e.getKeyCode();
				String msg = msgTextField.getText();
				if(keyCode == KeyEvent.VK_ENTER) {
					if(msg!=null && !"".equals(msg.trim())) {
						//trim()方法会去除字符串中前边和后边的空格
						//处理后把msg发送给服务器
						hander.sendMsgToServer(msg);
					}
				}
			}
		});
	}
	
	private void appendContent(String msg) {
		area.append(msg.trim()+"\n");
		msgTextField.setText("");
	}
	
	
	public static void main(String[] args) {
		new ClientGUITest();
	}
	
	
	private class Hander extends Thread{
		
		private String name;
		
		private Socket socket;
		private String ip;
		private int port;
		
		private BufferedReader in;
		private PrintWriter out;

		private String charsetName;
		
		public Hander(String name) {
			this.name = name;
			this.ip = "127.0.0.1";
			this.port = 8888;
			this.charsetName = "UTF-8";
		}
		
		@Override
		public void run() {
			
			try {
				socket = new Socket(ip, port);
				//读
				in = new BufferedReader(
						new InputStreamReader(socket.getInputStream(),charsetName));
				//写
				out = new PrintWriter(
						new OutputStreamWriter(socket.getOutputStream(),charsetName));
				
				this.sendMsgToServer(name);
				
				String msg = null;
				
				while((msg=in.readLine()) != null) {
					//追加到界面文本域
					appendContent(msg);
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				//关闭流
				try {
					if(in!=null)in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				try {
					if(out!=null)out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				try {
					if(socket!=null)socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
		
		public void sendMsgToServer(String msg) {
			out.println(msg);
			out.flush();
		}
		
	}
	
}
//服务器端
public class ServerSocketTest9 {
	
	private static List<MyThread> list = new ArrayList<>();
	
	public static void main(String[] args) {
		
		int port = 8888;
		ServerSocket server = null;
		Socket socket = null;
		try {
			server = new ServerSocket(port);
			
			//在指定的端口上,监听客户端的连接
			//accept方法或导致当前线程阻塞
			//一旦客户端连接上来了,accept方法阻塞结束,并返回连接的客户端对象
			System.out.println("服务器启动,监听端口号"+port);
			
			System.out.println("服务器正在等待新客户端连接");
			while(true) {
				socket = server.accept();
				
				System.out.println("服务器接收到客户端连接,当前连接的客户端为:"+socket);
				
				MyThread t = new MyThread(socket);
				t.start();
				
				list.add(t);
				
				System.out.println("服务器已经将接收的客户端连接,交给一个新的线程处理");
				System.out.println("服务器继续等待新的客户端连接");
			}
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(server!=null)server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	private static class MyThread extends Thread{
		
		private Socket socket;
		private BufferedReader in;
		private PrintWriter out;
		String charsetName = "UTF-8";
		
		public MyThread(Socket socket) {
			this.socket = socket;
		}
		
		@Override
		public void run() {
			
			
			try {
				in = new BufferedReader(
							new InputStreamReader(socket.getInputStream(),charsetName));
				
				out = new PrintWriter(
							new OutputStreamWriter(socket.getOutputStream(),charsetName));
				
				
				String name = in.readLine();
				
				while(true) {
					
					String msg = in.readLine();
					
					this.sendMsgToAll(name, msg);
					
					if("bye".equals(msg)) {
						break;
					}
				}
				
				
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				try {
					if(in!=null)in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					if(out!=null)out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				try {
					if(socket!=null)socket.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			
		}
		
		
		private void sendMsgToSelf(String name,String msg) {
			if(name == null) {
				name = "匿名用户";
			}
			out.println(name+": "+msg);
			out.flush();
		}
		
		private void sendMsgToAll(String name,String msg) {
			for(MyThread t:list) {
				if(t.isAlive() == true) {
					t.sendMsgToSelf(name, msg);
				}
			}
		}
		
		
		
		
	}
	
	
	
}
//客户端
public class SocketTest9 {
	public static void main(String[] args) {
		String ip = "127.0.0.1";
		int port = 8888;
		
		Socket socket = null;
		PrintWriter out = null;
		BufferedReader in = null;
		BufferedReader inFormConsole = null;
		
		try {
			//只要这个Socket对象能被创建出来
			//那么就说明当前程序已经通过ip和port连接到了服务端
			socket = new Socket(ip, port);
			System.out.println("客户端已经成功连接到了服务端("+ip+","+port+")");
			
			String charsetName = "UTF-8";
			
			out = new PrintWriter(
					new OutputStreamWriter(socket.getOutputStream(),charsetName));
			
			
			in = new BufferedReader(
					new InputStreamReader(socket.getInputStream(),charsetName));
			
			
			inFormConsole = 
					new BufferedReader(new InputStreamReader(System.in));
			
			
			Thread t = new MyThread(in);
			t.start();
			
			String line = in.readLine();
			System.out.println(line);
			
			String name = inFormConsole.readLine();
			out.println(name);
			out.flush();
			
			while(true) {
				
				//在eclipse的控制台中等待用户的键盘输入
				String lineFromConsole = inFormConsole.readLine();
				
				out.println(lineFromConsole);
				out.flush();
				
				if("bye".equals(lineFromConsole)) {
					t.interrupt();
					break;
				}
				
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(in!=null)in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(out!=null)out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if(inFormConsole!=null)inFormConsole.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(socket!=null)socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	
	private static class MyThread extends Thread{
		
		private BufferedReader in;
		
		public MyThread(BufferedReader in) {
			this.in = in;
		}
		
		@Override
		public void run() {
			
			while(super.isInterrupted() == false) {
				String lineFromServer;
				try {
					//读取服务器端写回的内容
					lineFromServer = in.readLine();
//					String[] arr = lineFromServer.split(": ");
//					if(arr.length==2 && "bye".equals(arr[1])) {
//						break;
//					}
					System.out.println(lineFromServer);
				} catch (IOException e) {
					e.printStackTrace();
//					break;
				}
			}
			
		}
		
	}
	
	
}

2020/4/29学习笔记day51_第1张图片
在这里插入图片描述
2020/4/29学习笔记day51_第2张图片

UDP

public class UDPClientTest {
	public static void main(String[] args) {
		
		DatagramPacket packet = null;
		DatagramSocket socket = null;
		
		String serverIp = "127.0.0.1";
		int serverPort = 9999;
		
		try {
			socket = new DatagramSocket();
			byte[] buf = "hello world".getBytes();
			
			InetAddress address = InetAddress.getByName(serverIp);
			packet = new DatagramPacket(buf, buf.length,address,serverPort);
			
			//使用socket把packet封装好的数据发送出去
			socket.send(packet);
			System.out.println("客户端发送数据完毕");
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(socket != null) socket.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
}
public class UDPServerTest {
	public static void main(String[] args) {
		
		DatagramPacket packet = null;
		DatagramSocket socket = null;
		
		byte[] buf = new byte[128];
		int port = 9999;
		
		try {
			socket = new DatagramSocket(port);
			packet = new DatagramPacket(buf, buf.length);
			socket.receive(packet);//接收数据
			String msg = new String(buf,0,packet.getLength());
			System.out.println("UDP接收数据:"+msg);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(socket != null) socket.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
}

在这里插入图片描述
在这里插入图片描述

URI和URL

2020/4/29学习笔记day51_第3张图片
URI是uniform resource identifier,**统一资源标识符,**用来唯一的标识一个资源。URI是以一种抽象的,高层次概念定义统一资源标识,而URL则是具体的一种资源标识的方式。
URL是uniform resource locator,统一资源定位器,它是一种具体的URI,即URL可以用来标识一个资源,而且还指明了如何locate这个资源。

在Java的URI中,一个URI实例可以代表绝对的,也可以是相对的,只要它符合URI的语法规则。而URL类则不仅符合语义,还包含了定位该资源的信息,因此它不能是相对的,schema(访问协议)必须被指定。

//是URI也是URL 标识+定位(可以通过地址访问到这个资源)
ftp://ftp.is.co.za/rfc/rfc1808.txt 
http://www.ietf.org/rfc/rfc2396.txt 
mailto:[email protected] 
telnet://192.0.2.16:80/ 

//URI标识(资源名字就是它的标识)
tel:+1-816-555-1212
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
/user/1
public class URLTest {
	public static void main(String[] args) {
		try {
			URL url = new URL("https://www.baidu.com/?name=tom#N1");

			// 获取与此 URL关联协议的默认端口号
			System.out.println("默认端口号 = " + url.getDefaultPort());
			// 获取此 URL的主机名
			System.out.println("主机名 = " + url.getHost());
			// 获取此 URL 的路径部分
			System.out.println("路径 = " + url.getPath());
			// 获取此 URL 的端口号,如果未设置端口号,则返回 -1
			System.out.println("指定端口= " + url.getPort());
			// 获取此 URL 的协议名称
			System.out.println("协议名称= " + url.getProtocol());
			// 获取此 URL 的查询部分
			System.out.println("查询参数= " + url.getQuery());
			// 获取此 URL的锚点
			System.out.println("Ref = " + url.getRef());

			// -------模拟浏览器向此URL发生请求----------------

			HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setRequestMethod("GET");
			httpConn.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0");
			InputStream is = httpConn.getInputStream();
			Reader in = new InputStreamReader(is);
			char[] cbuf = new char[1024];
			int len = -1;
			while ((len = in.read(cbuf)) != -1) {
				System.out.print(new String(cbuf, 0, len));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// close
		}
	}
}

你可能感兴趣的:(Web学习)