EchoContentHandler 类负责处理 EchoServer 服务器发送的数据
public class EchoContentHandler extends ContentHandler {
/** 读取服务器发送的一行数据,把它转换为字符串对象 */
public Object getContent(URLConnection connection) throws IOException {
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
return br.readLine();
}
public Object getContent(URLConnection connection, Class[] classes) throws IOException {
InputStream in = connection.getInputStream();
for(int i = 0; i < classes.length; i++) {
if(classes[i] == InputStream.class) {
return in;
} else if(classes[i] == String.class) {
return getContent(connection);
}
}
return null;
}
}
第二个 getContent() 方法依次遍历 classes 参数中的元素,判断元素是否为 InputSuream 类型或 String 类型,如果是,就返回相应类型的对象,它包含了服务器发送的数据。如果 classes 参数中的元素都不是 InputStream 类型或 String 类型,就返回 null
EchoContentHandlerFactory 类的 createContentHandler() 方法负责创建一个EchoContentHandler 对象
public class EchoContentHandlerFactory implements ContentHandlerFactory {
public ContentHandler createContentHandler(String mimetype) {
if(mimetype.equals("text/plain")) {
return new EchoContentHandler();
} else {
return null;
}
}
}
在客户程序中,可以通过以下方式设置 EchoContentHandlerFactory
URLConnection.setContentHandlerFactory(new EchoContentHandlerFactory());
URL url = new URL("echo://localhost:8000");
EchoURLConnection connection = (EchoURLConnection)url.openConnection();
...
//读取服务器返回的数据,它被包装为一个字符串对象
String echoMsg = (String)connection.getContent();
4. 在 EchoClient 类运用 ECHO 协议处理框架
public class EchoClient {
public static void main(String args[]) throws IOException {
//设置URLStreamHandlerFactory
URL.setURLStreamHandlerFactory(new EchoURLStreamHandlerFactory());
//设置ContentHandlerFactory
URLConnection.setContentHandlerFactory(new EchoContentHandlerFactory());
URL url = new URL("echo://localhost:8000");
EchoURLConnection connection = (EchoURlConnection) url.openConnection();
//允许获得输出流
connection.setDoOutput(true);
//获得输出流
PrintWriter pw = new PrintWriter(connection.getOutputStream(), true);
while(true) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msg = br.readLine();
//向服务器发送消息
pw.println(msg);
//读取服务器返回的消息
String echoMsg = (String) connection.getContent();
System.out.println(echoMsg);
if(echoMsg.equals("echo:bye")) {
//断开连接
connection.disconnect();
break;
}
}
}
}