2010-11-11 8 views
14

Ho un piccolo server HTTP qui scritto in C# e fino ad ora ho solo bisogno di inviare il testo non elaborato al mittente. Ma ora devo inviare un'immagine JPG e non riesco a capire come.C# invia l'immagine su HTTP

questo è quello che ho adesso:

// 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)); 

penso di dover fare una sorta di FileStream invece di una stringa, ma ho davvero nessuna colla ..

+0

Puoi pubblicare una parte del vostro metodo di handleRequest? Sto indovinando che è dove si sta costruendo l'oggetto HTTP Response che verrà inviato al browser che effettua la richiesta. Dovrai capire come modificarlo per supportare le immagini. –

+1

Ho un po 'di colla se si vuole prendere in prestito:/ – jlafay

+0

@ Martin se stai leggendo dal file puoi semplicemente chiamare socket.SendFile. vedere qui (msdn.microsoft.com/en-us/library/sx0a40c2.aspx –

risposta

1

Vuoi inviare da file o oggetto Bitmap?

MemoryStream myMemoryStream = new MemoryStream(); 
myImage.Save(myMemoryStream); 
myMemoryStream.Position = 0; 

EDIT

// Send the response 
SendVarData(socket,memoryStream.ToArray()); 

per l'invio MemoryStream da presa è possibile utilizzare questo metodo dato here

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; 
} 
+0

Ehh. C'è davvero un sovraccarico di invio che prende un flusso? – jgauffin

+0

@jgauffin - socket.SendFile() sarebbe l'opzione se si fosse interessati solo a inviando il file. Questo non fornirà comunque la formattazione di risposta HTTP appropriata necessaria per una risposta corretta. –

+0

non è quello che ho chiesto :) AFAIK non ci sono sovraccarichi che accettano un flusso come argomento. – jgauffin

1

Perché avete creato un httpserver da soli? Perché non usare uno open source? Per esempio il mio: http://webserver.codeplex.com

public class Example  
{ 
    private HttpListener _listener; 

    public void StartTutorial() 
    { 
     _listener = HttpListener.Create(IPAddress.Any, 8081); 
     _listener.RequestReceived += OnRequest; 
     _listener.Start(5); 
    } 

    private void OnRequest(object source, RequestEventArgs args) 
    { 
     IHttpClientContext context = (IHttpClientContext)source; 
     IHttpRequest request = args.Request; 

     IHttpResponse response = request.CreateResponse(context); 
     response.Body = new FileStream("Path\\to\\file.jpg"); 
     response.ContentType = "image\jpeg"; 
     response.Send(); 
    } 

} 

Modifica

Se si vuole veramente fare fare da soli:

string responseHeaders = "HTTP/1.1 200 The file is coming right up!\r\n" + 
"Server: MyOwnServer\r\n" + 
"Content-Length: " + new FileInfo("C:\\image.jpg").Length + "\r\n" + 
"Content-Type: image/jpeg\r\n" + 
"Content-Disposition: inline;filename=\"image.jpg;\"\r\n" + 
"\r\n"; 

//headers should ALWAYS be ascii. Never UTF8 
var headers = Encoding.ASCII.GetBytes(responseHeaders); 
socket.Send(headers, 0, headers.Length); 
socket.SendFile("C:\\image.jpg"); 
+0

perché è molto semplice e non si comporta come un HTTP Server .. Ricevo solo esempi di comandi: http: //localhost/winamp.play – Martin

+2

perché hai scritto un httpserver quando i server esistono già? –

+0

Davvero? Mostrami un server http che può essere incorporato in un'applicazione .Net 2.0. . Net HttpListener richiede i privilegi di amministrazione per poter iscriversi su determinati URL. Non molto flessibile. Il mio punto è che se non hai abbastanza conoscenza di HTTP probabilmente sprecherai un bel po 'di tempo cercando di far funzionare le cose. Dovrebbe essere più efficiente usare le librerie esistenti. – jgauffin