java---网络编程

☆樱花仙子☆ 提交于 2020-03-04 11:13:53
// =====================UDP网络编程===================================
	/**UDP
	 * 客户端端
	 * 创建DatagramSocket,随机端口
	 * 创建DatagramPacket指定数据、长度、地址、端口
	 * 使用DatagramSocket发送DatagramPacket
	 * 关闭DatagramSocket
	 */
	Scanner sc = new Scanner(System.in);
	DatagramSocket socket = new DatagramSocket();
	while (true) {
		String line = sc.nextLine();
		if("quit".equals(line)) {
			break;
		}
		DatagramPacket packet = 
				new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
		socket.send(packet);
		
	}
	socket.close();
	
	/**UDP
	 * 服务端
	 * 创建DatagramSocket,随机端口
	 * 创建DatagramPacket指定数据、长度、地址、端口
	 * 使用DatagramSocket发送DatagramPacket
	 * 关闭DatagramSocket
	 */
	DatagramSocket socket = new DatagramSocket(6666);
	DatagramPacket packet = new DatagramPacket(new byte[1024],1024);
	while (true) {
		socket.receive(packet);
		byte[] arr = packet.getData();
		int len = packet.getLength();
		String ipString = packet.getAddress().getHostAddress();
		int port = packet.getPort();
		System.out.println(ipString +":"+port+"//"+new String(arr,0,len));
	}
	
	// =====================TCP网络编程===================================

	/**TCP
	 * 客户端
	 */
	Scanner sc = new Scanner(System.in);
	String str = sc.nextLine();
	Socket socket = new Socket("127.0.0.1", 6666);
	BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
	PrintStream ps = new PrintStream(socket.getOutputStream());
	ps.println(str);
	System.out.println(br.readLine());
	socket.close();
	
	/**TCP
	 * 服务端
	 */
	ServerSocket server = new ServerSocket(6666);
	System.out.println("服务器启动,监听6666端口");
	while (true) {
		Socket socket = server.accept();
		new Thread() {
			public void run() {
				try {
					BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					PrintStream ps = new PrintStream(socket.getOutputStream());
					String str = br.readLine();
					System.out.println("接收的是:"+str);
					str = new StringBuilder(str).reverse().toString();
					ps.println(str);
					
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
	}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!