package com.hvgroup.sockethttpproxy;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
/**
* Socket服务处理类
* @author suhx
* 2016年11月25日 下午3:46:53
*/
public class SocketServerHandler implements Runnable {
private Socket socket;
public SocketServerHandler(Socket client) {
socket = client;
new Thread(this).start();
}
/**
* @功能 读取流
* @param inStream
* @return 字节数组
* @throws Exception
*/
public static byte[] readStream(InputStream inStream) throws Exception {
int count = 0;
while (count == 0) {
count = inStream.available();
}
byte[] b = new byte[count];
inStream.read(b);
return b;
}
/**
* 代理发起HTTP请求,并返回结果
* @return
*/
public String proxyHttpRequest(String request){
String result = null;
try {
URL url = new URL(request);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
result = new String(readStream(in),"utf-8");
} catch (Exception e) {
result = e.getMessage();
e.printStackTrace();
}
return result;
}
public void run() {
try {
// 读取客户端数据
DataInputStream input = new DataInputStream(socket.getInputStream());
String clientInputStr = input.readUTF();// 这里要注意和客户端输出流的写方法对应
System.out.println("$-请求:\n"+clientInputStr);
// 转发请求获取结果
String result = proxyHttpRequest(clientInputStr);
System.out.println("$-应答:\n"+result);
// 向客户端回复信息
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF(result);
out.close();
input.close();
} catch (Exception e) {
System.out.println("$-服务器 run 异常: " + e.getMessage());
} finally {
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
socket = null;
System.out.println("$-服务端 finally 异常:" + e.getMessage());
}
}
}
}
}