Welcome to Yumao′s Blog.
最近經常聼的一個網絡電臺換了網路
導致直連一直聼的頓頓的
連玩游戯的心情都失去了
後來就在想 既然我有這麽多閒置的服務器
爲什麼不用一個網路好點的國外服務器做轉發
嗯 想到了這方面就蠢蠢欲動了
因爲毛毛我還是對java語言最熟悉
所以還是想著用最基本的servlet寫寫試試好了
以前是有做過http訪問方面的
所以向上游訪問就用HttpClient擔任了
總體思路就是使用httpClient獲取stream
然後服務器進行stream的轉發
或者copy下發(暫無需求 所以就沒做)
成果代碼如下
只用了HttpClient的庫
以及一個jsp文件而已(算是很偷懶了)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page language="java" import="java.io.*"%>
<%@ page language="java" import="org.apache.http.client.HttpClient"%>
<%@ page language="java" import="org.apache.http.HttpEntity"%>
<%@ page language="java" import="org.apache.http.HttpResponse"%>
<%@ page language="java" import="org.apache.http.client.methods.HttpGet"%>
<%@ page language="java" import="org.apache.http.impl.client.DefaultHttpClient"%>
<%
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("http://radio.phate.cc/listen");
HttpResponse repon = httpClient.execute(get);
HttpEntity entity = repon.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int bytesRead = 0;
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
while ((bytesRead = instream.read())!=-1) {
toClient.write(bytesRead);
toClient.flush();
}
toClient.close();
}
get.abort();
%>
此轉發也可以用作網頁等任何http數據轉發喔
當然你要想辦法繞過偉大的功夫網而已
一個要點是:
本來我最初的代碼是將stream先用byte數組處理
然後一個包一個包的發
最後發現這樣處理之後
音頻流經常出現斷幀噪音
所以流媒體還是直接轉發就好
畢竟原本就是小包多傳保證實時效果
你將其攔截封了發肯定出問題的呀
當然web的轉發就是可以封了發哦
順帶給出我原來的錯誤方法(可以適用於web)
HttpClient httpClient = new DefaultHttpClient();
BASE64Decoder bASE64Decoder = new BASE64Decoder();
HttpGet get = new HttpGet(new String(bASE64Decoder.decodeBuffer(request.getParameter("url"))));
HttpResponse repon = httpClient.execute(get);
HttpEntity entity = repon.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int bytesRead = 0;
byte[] buffer = new byte[8];
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
while ((bytesRead = instream.read(buffer, 0, 8)) != -1) {
toClient.write(buffer);
toClient.flush();
}
toClient.close();
}
get.abort();
當時還調整了很多次byte數組的容量
最後發現不妥 做不到完美
so…..
思考東西總是繞路的我
哈~