• 0

Sending Images over HTTP


Question

I'm writing a web server in Tcl

HTML pages can be served fine but whenever I serve an image (of any format)

the browser always complains that it contains errors and cannot be displayed...

I tested it manually in telnet and it seems to send a load of ascii over which I assume is the image..

What special thing needs to be done to send an image?

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0
I'm writing a web server in Tcl

HTML pages can be served fine but whenever I serve an image (of any format)

the browser always complains that it contains errors and cannot be displayed...

I tested it manually in telnet and it seems to send a load of ascii over which I assume is the image..

What special thing needs to be done to send an image?

584787030[/snapback]

you need to use sock_mode() to change the TCP socket to send in binary mode. Sending in ASCII mode will screw up your image data.

Link to comment
Share on other sites

  • 0

#!/usr/bin/tclsh

proc Start_server {} {
	global socks
	set socks(svr) [socket -server Get_connection 2000]
}
proc Get_connection {sock addr 2000} {
	global socks
	fconfigure $sock -buffering line
	fileevent $sock readable [list Read_line $sock]
}

proc Html_header {client_sock} {
	puts $client_sock "HTTP /1.0 200 OK"
	puts $client_sock "Server: Skin Up"
	puts $client_sock "Content-Type: text/html"
	puts $client_sock ""
}

proc Image_header {client_sock} {
	puts $client_sock "HTTP /1.0 200 OK"
	puts $client_sock "Server: Skin Up"
	puts $client_sock "Content-Type: image/jpg"
	puts $client_sock ""
}

proc Send_page {client_sock file_name} {
	set file_eater [open $file_name r]
	set file_data [read $file_eater]
	close $file_eater
	set file_data [split $file_data "\n"]  
	foreach line $file_data {
  puts $client_sock $line
	}
}

proc Read_line {client_sock} {
	set line_from [gets $client_sock]
	set request_string [split $line_from]
	if [string match [lindex $request_string 0] "GET"] {
  puts stdout [lindex $request_string 1]
  
  set file_name [lindex $request_string 1]
  set file_parts [split $file_name "."]
  if [string match [lindex $file_parts 1] "html"] {
 	 Html_header $client_sock  
  }
  
  if [string match [lindex $file_parts 1] "jpg"] {
 	 Image_header $client_sock
 	 fconfigure $client_sock -translation binary

  }

  set file_to_send [lindex $request_string 1] 
  if [string match $file_to_send "/"] {
 	 set $file_to_send "/index.html"
  }

  Send_page $client_sock "/home/john$file_to_send"
  close $client_sock
	} 

}

Start_server
vwait forever

this is the code if there's anything obvious in there...

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.