1 socket模拟浏览器
/**
* tcp 模拟 浏览器
* Created by Administrator on 2018/8/26.
*/
public class TcpClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 80);
// 拼接请求报文
// 请求行
String request_line = "GET /servlet/helloServlet HTTP/1.1\r\n";
// 请求头
String request_head = "Host:\r\n";
String request = request_line + request_head + "\r\n";
// 发送请求
OutputStream outputStream = socket.getOutputStream();
outputStream.write(request.getBytes());
// 获取结果
InputStream inputStream = socket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
byte[] buf = new byte[1024];
int len;
while (-1 != (len = bis.read(buf))) {
System.out.println(new String(buf, 0, len));
}
outputStream.close();
inputStream.close();
socket.close();
}
}
2. 自实现 Jedis
/**
* 自定义 Jedis (jedis 通过 socket 与 redis 通信)
* Created by Administrator on 2018/8/26.
*/
public class MyJedis {
private Socket socket;
public MyJedis(String host, int port) {
try {
socket = new Socket(host, port);
} catch (IOException e) {
e.printStackTrace();
}
}
// RESP redis序列化协议
public String set(final String key, String value) throws IOException {
StringBuilder line = new StringBuilder();
line.append("*3").append("\r\n");
line.append("$3").append("\r\n");
line.append("SET").append("\r\n");
line.append("$").append(key.length()).append("\r\n");
line.append(key).append("\r\n");
line.append("$").append(value.length()).append("\r\n");
line.append(value).append("\r\n");
OutputStream outputStream = socket.getOutputStream();
outputStream.write(line.toString().getBytes());
InputStream inputStream = socket.getInputStream();
byte[] buf = new byte[1024];
inputStream.read(buf);
String result = new String(buf);
System.out.println(result);
return result;
}
public String get(final String key) throws IOException {
StringBuilder line = new StringBuilder();
line.append("*2").append("\r\n");
line.append("$3").append("\r\n");
line.append("GET").append("\r\n");
line.append("$").append(key.length()).append("\r\n");
line.append(key).append("\r\n");
OutputStream outputStream = socket.getOutputStream();
outputStream.write(line.toString().getBytes());
InputStream inputStream = socket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
byte[] buf = new byte[1024];
StringBuilder result = new StringBuilder();
bis.read(buf);
result.append(new String(buf));
outputStream.close();
bis.close();
return result.toString();
}
public static void main(String[] args) throws IOException {
MyJedis myJedis = new MyJedis("192.168.121.102", 6379);
myJedis.set("myJdeis", "wjb is good");
String value = myJedis.get("myJdeis");
System.out.println(value);
myJedis.socket.close();
}
}