static FileSystem fs;
static {
try {
// 打开文件通道,uri里面是虚拟机的地址
// fs为对hdfs文件进行操作的对象
fs = FileSystem.get(new URI("hdfs://192.168.56.100:9000"),new Configuration());
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
open和create方法分别为读和写,fs方法
service类:
// 开启服务器后再开启客户端
public static void main(String[] args) throws Exception{
// 设置服务器端口,必须唯一
ServerSocket sck = new ServerSocket(60000);
// 死循环服务器一直在工作直到输入exit退出
while(true) {
// 等别人给信息,监听到别的程序的输出流
Socket socket = sck.accept();
// 输入流,即读
InputStream is = socket.getInputStream( );
// 输入缓冲流
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String info = null;
boolean flag = false;
while (!((info = br.readLine()) == null)) {
System.out.println("服务器收到来自客户端的信息:" + info);
if (info.equalsIgnoreCase("exit")) {
flag = true;
}
}
if (flag) {
break;
}
// continue下面的close方法就不执行转到最上面去执行
if (info == null && !flag) {
continue;
}
is.close();
br.close();
socket.close();
}
sck.close();
}
client类:
@Override
public void run() {
try {
for (int i = 0; i < 50000; i++) {
// 我的ip地址,因为两个程序运行在一个机器上,所以写localhost,窗口设定一致
Socket socket = new Socket("localhost", 60000);
// 输出流
OutputStream os = socket.getOutputStream();
String clientInfo = "I am "+i;
// 字符串输出
os.write(clientInfo.getBytes());
os.close();
socket.close();
Thread.sleep(3);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}