Hello world/Web server: Difference between revisions
Content added Content deleted
m (→{{header|Phix}}: builtins/sockets.e modified/documented, now polls for esc/Q, added output) |
|||
Line 1,410: | Line 1,410: | ||
Output as C, code is however a translation of a FASM example. |
Output as C, code is however a translation of a FASM example. |
||
<lang Phix>-- demo\rosetta\SimpleHttpServer.exw |
<lang Phix>-- demo\rosetta\SimpleHttpServer.exw |
||
include builtins\sockets.e |
include builtins\sockets.e |
||
constant MAX_QUEUE = 100, |
constant MAX_QUEUE = 100, |
||
ESCAPE = #1B, |
ESCAPE = #1B, |
||
response = 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 |
HTTP/1.1 200 OK |
||
Content-Type: text/html; charset=UTF-8 |
Content-Type: text/html; charset=UTF-8 |
||
Line 1,440: | Line 1,434: | ||
""","\n","\r\n") |
""","\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) |
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 |
|||
⚫ | |||
if listen(sock,MAX_QUEUE)=SOCKET_ERROR then crash("listen (%v)",{get_socket_error()}) end if |
|||
⚫ | |||
⚫ | |||
ip = get_sin_addr(sock_addr) |
|||
integer |
{integer code} = select({sock},{},{},250000) -- (0.25s) |
||
if code=SOCKET_ERROR then crash("select") end if |
|||
string request = peek({buffer,len}) |
|||
if code>0 then -- (not timeout) |
|||
⚫ | |||
⚫ | |||
⚫ | |||
ip = getsockaddr(peer) |
|||
{integer len, string request} = recv(peer) |
|||
send(peer,buffer,length(response),0) |
|||
⚫ | |||
⚫ | |||
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 if |
||
end while |
end while |
||
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}}== |
=={{header|PHP}}== |