[Libwebsockets] How to send reason phrase in http response from server to client

Andy Green andy at warmcat.com
Tue Aug 23 15:34:10 CEST 2016


On Tue, 2016-08-23 at 18:45 +0530, Gadkari, Mugdha wrote:
> Hello,
>  
> In my server client implementation of libwebsockets, whenever client
> sends wrong key, server says 400 Bad request. But I need a way to
> send message along with this response to notify client that this 400
> Error is because of wrong key. As per HTTP protocol, server can reply
> with a reason phrase for connection denial. (https://tools.ietf.org/h
> tml/rfc2616#page-39)
>  
> I tried handling this in
> server LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION, I tried sending a
> message using lws_write() with LWS_WRITE_HTTP method, but client is
> not receiving the message. I 

The server must send a correctly-formed HTTP reply with appropriate
headers, you can't just throw a text message at it.

> get LWS_CALLBACK_CLIENT_CONNECTION_ERROR in client but no response
> reason from server.  
>  
> Can anyone please provide information about sending a reason phrase
> in server reply?

At least in recent lws there's a helper if the text (which may be html)
you want to send is < ~400 bytes.

LWS_VISIBLE LWS_EXTERN int
lws_return_http_status(struct lws *wsi, unsigned int code,
		       const char *html_body);

libwebsockets.h also gives you the standard reason codes from a nice
enum, eg HTTP_STATUS_BAD_REQUEST.

The helper is nice because he correctly formats everything also for
http/2 transparently if that's needed.

You'd do something like

		if
(lws_return_http_status(wsi, HTTP_STATUS_BAD_REQUEST, "Wrong special
key"))
			return -1;

		if (lws_http_transaction_completed(wsi))
			return -1;

The client will see a page like

404
Wrong special key

-Andy

> Thanks in advance
>  
> Regards,
> Mugdha
>  
>  
> _______________________________________________
> Libwebsockets mailing list
> Libwebsockets at ml.libwebsockets.org
> http://libwebsockets.org/mailman/listinfo/libwebsockets



More information about the Libwebsockets mailing list