1.1 協議
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.VersionedProtocol;
public interface MyProtocol extendsVersionedProtocol {
public Text test(Text t);
}
1.2 客戶端
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.RPC;
public class MyClient {
public MyProtocol myProtocol;
public MyClient() throws IOException {
InetSocketAddress addr = new InetSocketAddress("localhost", 8888);
myProtocol = (MyProtocol)RPC.waitForProxy(MyProtocol.class, 1, addr,
new Configuration());
}
public void sendClientMsg() {
System.out.println("I am client,waiting server's data...");
Text result = myProtocol.test(new Text("message from client"));
System.out.println(result.toString());
}
public static void main(String[] args) throws IOException {
MyClient client = new MyClient();
client.sendClientMsg();
}
}
1.3 服務端
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RPC.Server;
public class MyServer implements MyProtocol {
public void initialize() throws InterruptedException, IOException {
Server server =RPC.getServer(this, "localhost", 8888,
new Configuration());
server.start();
}
@Override
public long getProtocolVersion(String s1, long s2) throws IOException {
return 1;
}
@Override
public Text test(Text t) {
if ("message from client".equals(t.toString()))
return new Text("data from server");
return new Text("who are you");
}
public static void main(String[] args) throws InterruptedException,
IOException {
MyServer server = new MyServer();
server.initialize();
}
}