package com.bill.rpc01;
import com.bill.rpc.common.User;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
/**
* @Auther: wangchunwen
* @Date: 2023/1/2 - 01 - 02 - 22:31
* @Description: com.bill.rpc01
* @version: 1.0
*/
public class Client {
public static void main(String[] args) throws IOException {
// 写出去
Socket s = new Socket("127.0.0.1",8888);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(123);
s.getOutputStream().write(baos.toByteArray());
s.getOutputStream().flush();
// 读进来
DataInputStream dis = new DataInputStream(s.getInputStream());
int id = dis.readInt();
String name = dis.readUTF();
User user = new User(id,name);
System.out.println(user);
dos.close();
s.close();
}
}
将网络通信的工作抽离出来,单独抽象为一个类,这个类的作用就是相当于1个网络通信的一个代理,屏蔽了一些网络通信实现的相关的细节。
package com.bill.rpc02;
import com.bill.rpc.common.User;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
/**
* @Auther: wangchunwen
* @Date: 2023/1/2 - 01 - 02 - 22:42
* @Description: com.bill.rpc02
* @version: 1.0
*/
public class Stub {
public User findUser(Integer id) throws IOException {
Socket s = new Socket("127.0.0.1",8888);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(123);
s.getOutputStream().write(baos.toByteArray());
s.getOutputStream().flush();
DataInputStream dis = new DataInputStream(s.getInputStream());
int receivedId = dis.readInt();
String name = dis.readUTF();
User user = new User(receivedId,name);
dos.close();
dos.close();
return user;
}
}
标签:java,230102,50,RPC,dos,User,io,new,import
From: https://www.cnblogs.com/wcwblog/p/17020792.html