C#通过HTTP发送图像

mar*_*yyy 15 c# tcplistener image http send

我有一个用C#编写的小型HTTP服务器,直到现在我只需要将原始文本发送回发件人.但现在我必须发送一个JPG-Image,我不知道如何.

这就是我现在拥有的:

// Read the HTTP Request
Byte[] bReceive = new Byte[MAXBUFFERSIZE];
int i = socket.Receive(bReceive, bReceive.Length, 0);

//Convert Byte to String
string sBuffer = Encoding.ASCII.GetString(bReceive);

// Look for HTTP request
iStartPos = sBuffer.IndexOf("HTTP", 1);

// Extract the Command without GET_/ at the beginning and _HTTP at the end
sRequest = sBuffer.Substring(5, iStartPos - 1 - 5);
String answer = handleRequest(sRequest);


// Send the response
socket.Send(Encoding.UTF8.GetBytes(answer));
Run Code Online (Sandbox Code Playgroud)

我想我必须做一些文件流而不是字符串,但我真的没有胶水..

Ars*_*yan 2

您想从文件还是位图对象发送?

MemoryStream myMemoryStream = new MemoryStream();
myImage.Save(myMemoryStream);
myMemoryStream.Position = 0;
Run Code Online (Sandbox Code Playgroud)

编辑

// Send the response
SendVarData(socket,memoryStream.ToArray());
Run Code Online (Sandbox Code Playgroud)

要通过套接字发送 MemoryStream,您可以使用此处给出的方法

 private static int SendVarData(Socket s, byte[] data)
 {
            int total = 0;
            int size = data.Length;
            int dataleft = size;
            int sent;

            byte[] datasize = new byte[4];
            datasize = BitConverter.GetBytes(size);
            sent = s.Send(datasize);

            while (total < size)
            {
                sent = s.Send(data, total, dataleft, SocketFlags.None);
                total += sent;
                dataleft -= sent;
            }
            return total;
 }
Run Code Online (Sandbox Code Playgroud)