⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 musicdataclient.java

📁 《Java核心技术应用开发》电子工业出版社书籍源代码
💻 JAVA
字号:
import java.io.*;
import java.net.*;
import java.util.*;

/**
 *   这个类连接数据服务器来获得数据
 *   
 */
public class MusicDataClient implements StoneForestProtocol {

	/**
	 *  socket引用
	 */
	protected Socket hostSocket;

	/**
	 *  输出流的引用
	 */
	protected ObjectOutputStream outputToServer; 

	/**
	 *  输入流的引用
	 */
	protected ObjectInputStream inputFromServer;
	
	/**
	 *  默认构造方法
	 */
	public MusicDataClient() throws IOException {
		this(StoneForestProtocol.DEFAULT_HOST, StoneForestProtocol.DEFAULT_PORT);
	}
	
	/**
	 *  接受主机名和端口号的构造方法
	 */
	public MusicDataClient(String hostName, int port) throws IOException {

		log("连接数据服务器..." + hostName + ":" + port);
		
		hostSocket = new Socket(hostName, port);
		outputToServer = new ObjectOutputStream(hostSocket.getOutputStream());
		inputFromServer = new ObjectInputStream(hostSocket.getInputStream());
				
		log("连接成功.");
	}
	
	/**
	 *  返回类别集合
	 */
	public ArrayList getCategories() throws IOException {

		ArrayList categoryList = null;

		try {		
			log("发送请求: OP_GET_MUSIC_CATEGORIES");
			outputToServer.writeInt(StoneForestProtocol.OP_GET_MUSIC_CATEGORIES);
			outputToServer.flush();

			log("接收数据...");
			categoryList = (ArrayList) inputFromServer.readObject();
			log("收到 " + categoryList.size() + " 类别.");
		}
		catch (ClassNotFoundException exc) {
			log("=====>>>  异常: " + exc);
			throw new IOException("找不到相关类");
		}

		return categoryList;
	}
	
	/**
	 *  返回CD集合
	 */
	public ArrayList getRecordings(String category) throws IOException {

		ArrayList recordingList = null;

		try {
			log("发送请求: OP_GET_MUSIC_RECORDINGS  类别 = " + category);
			outputToServer.writeInt(StoneForestProtocol.OP_GET_MUSIC_RECORDINGS);
			outputToServer.writeObject(category);
			outputToServer.flush();

			log("接收数据...");
			recordingList = (ArrayList) inputFromServer.readObject();
			log("收到 " + recordingList.size() + " 唱片.");
		}
		catch (ClassNotFoundException exc) {
			log("=====>>>  异常: " + exc);
			throw new IOException("找不到相关类");
		}
		
		return recordingList;
	}
	

	/**
	 * 日志方法.
	 */
	protected void log(Object msg) {
		System.out.println("MusicDataClient类: " + msg);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -