利用 socket 獲取 tcp 包并解析的問題。
服務(wù)器端代碼如下:(Java Servlet 實現(xiàn))
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
OutputStream out = response.getOutputStream();
try {
response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(out, chart, 400, 300); // 將圖片寫入out中
response.flushBuffer();
}
catch (Exception e) {
System.err.println(e.toString());
}
finally {
out.close();
}
}
////////////////////////////////////////////////////////////////////////////////////
// 以下是客戶端代碼,通過socket取出TCP包,并解析
////////////////////////////////////////////////////////////////////////////////////
string request = "GET /PDAChart/ChartServlet?Chart=PieChart HTTP/1.1\r\n" + // 請求消息
"Host: " + server + ":" + port.ToString() + "\r\n" + // 主機和端口
"Connection: Close\r\n" + // 連接狀態(tài)
"\r\n";
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
Byte[] bytesReceived = new Byte[256];
// 創(chuàng)建Socket對象
Socket s = ConnectSocket(server, port);
if (s == null)
return ("Connection failed");
// 向服務(wù)器發(fā)送請求
s.Send(bytesSent, bytesSent.Length, 0);
// 接收服務(wù)器頁面內(nèi)容
int bytes = 0;
string page = "Default HTML page on " + server + ":\r\n";
// 安裝一定的塊接收數(shù)據(jù)
do
{
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes); // 將數(shù)據(jù)轉(zhuǎn)換為字符串
}
while (bytes > 0);
/////////////////////////////////////////////////////////////////////////////////////
// 解析 tcp包 查找\r\n\r\n
int index = page.IndexOf("\r\n\r\n");
Console.WriteLine(page.Substring(0,index)); // 取出TCP包頭
// 當(dāng)TCP包體的內(nèi)容也是文本的時候,沒有問題
Console.WriteLine(page.Substring(index + 4)); // 輸出包體
// 問題是當(dāng)包體是圖片的時候,該怎么處理呢????
// 我是這樣考慮的:scoket接收的時候,已經(jīng)將byte安裝ASCII轉(zhuǎn)換成string,這里將string轉(zhuǎn)換為byte,然后存成文件。
// 問題是最后存成的文件用圖片查看器打開以后是空的,什么都看不到。不過文件的大小是有的13k。
Byte[] byteArray = Encoding.ASCII.GetBytes(page.Substring(index + 4)); // page.Substring(index + 4)為包體內(nèi)容
using (BinaryWriter binWriter =
new BinaryWriter(File.Open("c:\\map.png", FileMode.Create)))
{
binWriter.Write(byteArray);
}
問題:
為什么我保存的圖片不能顯示呢?既然通過IE就可以看到圖片,就說明服務(wù)器端生成的內(nèi)容是沒有問題的。希望大家多給指點。
出處:http://mjgforever.cnblogs.com/
本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明。
posted on 2008-02-26 12:57 mjgforever 閱讀(1624) 評論(0) 收藏 舉報
浙公網(wǎng)安備 33010602011771號