悬赏园豆:5
[已关闭问题]
关闭于 2008-06-05 17:23
<P>服务器端代码如下:(Java Servlet 实现)<BR>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<BR> OutputStream out = response.getOutputStream();<BR> try {<BR> response.setContentType("image/png");<BR> ChartUtilities.writeChartAsPNG(out, chart, 400, 300); // 将图片写入out中<BR> response.flushBuffer(); <BR> }<BR> catch (Exception e) {<BR> System.err.println(e.toString());<BR> }<BR> finally {<BR> out.close();<BR> }<BR>} </P>
<P><BR>////////////////////////////////////////////////////////////////////////////////////<BR>// 以下是客户端代码,通过socket取出TCP包,并解析<BR>////////////////////////////////////////////////////////////////////////////////////<BR> string request = "GET /PDAChart/ChartServlet?Chart=PieChart HTTP/1.1\r\n" + // 请求消息<BR> "Host: " + server + ":" + port.ToString() + "\r\n" + // 主机和端口<BR> "Connection: Close\r\n" + // 连接状态<BR> "\r\n";<BR> Byte[] bytesSent = Encoding.ASCII.GetBytes(request);<BR> Byte[] bytesReceived = new Byte[256];</P>
<P> // 创建Socket对象<BR> Socket s = ConnectSocket(server, port);</P>
<P> if (s == null)<BR> return ("Connection failed");</P>
<P> // 向服务器发送请求<BR> s.Send(bytesSen
问题补充:
// 向服务器发送请求
s.Send(bytesSent, bytesSent.Length, 0);
// 接收服务器页面内容
int bytes = 0;
string page = "Default HTML page on " + server + ":\r\n";
// 安装一定的块接收数据
do
{
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes); // 将数据转换为字符串
}
while (bytes > 0);
/////////////////////////////////////////////////////////////////////////////////////
// 解析 tcp包 查找\r\n\r\n
int index = page.IndexOf("\r\n\r\n");
Console.WriteLine(page.Substring(0,index)); // 取出TCP包头
// 当TCP包体的内容也是文本的时候,没有问题
Console.WriteLine(page.Substring(index + 4)); // 输出包体
// 问题是当包体是图片的时候,该怎么处理呢????
// 我是这样考虑的:scoket接收的时候,已经将byte安装ASCII转换成string,这里将string转换为byte,然后存成文件。
// 问题是最后存成的文件用图片查看器打开以后是空的,什么都看不到。不过文件的大小是有的13k。
Byte[] byteArray = Encoding.ASCII.GetBytes(page.Substring(index + 4)); // page.Substring(index + 4)为包体内容
using (BinaryWriter binWriter =
new BinaryWriter(File.Open("c:\\map.png", FileMode.Create)))
{
binWriter.Write(byteArray);
}
问题:
为什么我保存的图片不能显示呢?既然通过IE就可以看到图片,就说明服务器端生成的内容是没有问题的。希望大家多给指点。