I am coding with libwebsockets
for client which is websocket library for C.
And i want to use websocket file descriptor with select()
so that i can handle websocket while handling other events.
and then only if websocket got an event, i can call libwebsocket_service();
to handle websocket event.
So i tried below steps.
Connect websocket through
struct libwebsocket *wsi = libwebsocket_client_connect(..)
I did also check if the reture value is NULL or not for error.Get file descriptor through int
fd = libwebsocket_get_socket_fd(wsi);
FD_SET(fd, &readFd);
andselect(maxFd + 1, &readFd, NULL, NULL, NULL);
But it keeps being blocked, though i think it must be wake up since server send message after connection is completed.
---EDIT----
After more testing.
It seems because select() is called before connection is completed. It means before handling LWS_CALLBACK_CLIENT_ESTABLISHED.
I put libwebsocket_service()
one more between libwebsocket_client_connect()
and select()
, so that it can handle LWS_CALLBACK_CLIENT_ESTABLISHED
before calling select()
.
And then it works with select() when it receive some message from server.
It means socket is normally open after handling LWS_CALLBACK_CLIENT_ESTABLISHED
?
You are trying to push water up hill.
Caveat: I've only written a server that does this, not a client; however, the interface is very similar
Firstly,
libwebsockets
is written on the basis you will usepoll
orppoll
rather thanselect
. I'm sure it's possible to useselect
, but your life will be much easier if you usepoll
orppoll
; rewriting myselect()
code to useppoll
took about 10 minutes. If you really want to useselect
, I suggest you get external polling working usingppoll
, then rewrite to useselect()
.Next, look at
test-server.c
, and specifically how the code changes ifEXTERNAL_POLL
is defined. You also want to read this bit of the API documentation:What this is saying (simply put) is that libwebsockets will call you with these methods and ask you to manipulate your
poll
array.Ignoring some complications about locking, you can see
test-server.c
has them implemented thus:I don't believe (sever side) you need to implement the second two callbacks,
test-server.c
does not, and I do not.After you call
poll
, you need to requestlibwebsockets
to service its own FDs, like so (again fromtest-server.c
):So, let's go back to your specific questions:
Well, apart from the impedance mismatch between
select
andpoll
, your problem here would appear to be thata) you are unconditionally saying the websocket is to be polled for reading, and
b) you are never saying you have data to write to the web socket.
You need to do
FD_SET
(andFD_CLEAR
) on both the read and write FDs as and when you get the appropriate callbacks. You are not doing that. This will cause problems.