Jump to content

Hello world/Web server: Difference between revisions

m
→‎{{header|Phix}}: builtins/sockets.e modified/documented, now polls for esc/Q, added output
m (→‎{{header|Phix}}: builtins/sockets.e modified/documented, now polls for esc/Q, added output)
Line 1,410:
Output as C, code is however a translation of a FASM example.
<lang Phix>-- demo\rosetta\SimpleHttpServer.exw
include builtins\sockets.e -- added for 0.8.1 (not yet documented)
 
constant MAX_QUEUE = 100,
ESCAPE = #1B,
BUFFER_SIZE response = 2048,substitute("""
buffer = allocate(BUFFER_SIZE),
sock_addr = new_sock_addr(AF_INET, 8080, NULL),
peerAddr = new_sock_addr(),
 
response = substitute("""
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Line 1,440 ⟶ 1,434:
""","\n","\r\n")
 
puts(1,"server started, open http://localhost:8080/ in browser or curl, press Esc or Q to quit\n")
atom sock = socket(AF_INET,SOCK_STREAM,NULL),
bind(sock,sock_addr)
pSockAddr = sockaddr_in(AF_INET, "", 8080)
listen(sock,MAX_QUEUE)
if bind(sock, pSockAddr)=SOCKET_ERROR then crash("bind (%v)",{get_socket_error()}) end if
while get_key()!=ESCAPE do
if listen(sock,MAX_QUEUE)=SOCKET_ERROR then crash("listen (%v)",{get_socket_error()}) end if
atom peer = accept(sock,peerAddr),
while not find(get_key()!=,{ESCAPE,'q','Q'}) do
ip = get_sin_addr(sock_addr)
{integer lencode} = recvselect(peer{sock},buffer{},BUFFER_SIZE{},250000) -- (0.25s)
if code=SOCKET_ERROR then crash("select") end if
string request = peek({buffer,len})
if code>0 then -- (not timeout)
printf(1,"Client IP: %s\n%s\n",{ip_to_string(ip),request})
atom peer = accept(sock,peerAddr),
if length(request)>3 and request[1..4]="GET " then
poke ip = getsockaddr(buffer,responsepeer)
{integer len, string request} = recv(peer)
send(peer,buffer,length(response),0)
printf(1,"Client IP: %s\n%s\n",{ip_to_string(ip),request})
if length(request)>3 and request[1..4]="GET " then
integer bytes_sent = send(peer,response)
printf(1,"%d bytes successfully sent\n",bytes_sent)
end if
shutdown(peer, SD_SEND) -- tell curl it's over
closesocket(peer) -- (as does this)
end if
end while</lang>
closesocket(sock)
WSACleanup()</lang>
{{Out}}
Server console, one you have opened http://localhost:8080 in your browser, or run curl http://localhost:8080
<pre>
server started, open http://localhost:8080/ in browser or curl, press Esc or Q to quit
Client IP: 127.0.0.1
GET / HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.55.1
Accept: */*
 
352 bytes successfully sent
</pre>
 
=={{header|PHP}}==
7,805

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.