For example for an undergrad CS/ECE course, say Intro to Computer Networks, there are about 5 textbooks published by the top 15 publishers in the last 20 years. Why aren't there way more textbooks, since there are probably tens of thousands of people (academics) who have the necessary knowledge to write such a book.
Is it because:
publishers don't publish a book about a topic for which they already published a book previously;
or academics don't think writing a textbook is beneficial for their careers and royalties are very low?
Wow, what a lot of negativity re writing textbooks. Let me offer a more positive perspective, at least in the field of mathematics. I've written seven textbooks over 30+ years, some solo, some with colleagues. One is at a beginning undergraduate level, two are at an advanced undergraduate level, and four are graduate texts. The first was written primarily while I was a post-doc and appeared as I was applying for tenure track jobs, the second was written while I was in a tenure-track position. Yes, they were a lot of work; the rule of thumb I've learned (for me) is to estimate the amount of time it should take, and then triple it. Would I have done better, career-wise, to have spent more time on research. Possibly, who can know, but I'm satisfied with how things have turned out.
My personal answer to "why write a textbook" is primarily:
Here's am area of mathematics that I love, and I'm writing the book that I wish that I'd had available when I was learning the subject.
Or, in a similar vein, the undergraduate cryptography textbook that I wrote with two colleagues is designed for a course that we teach, and it presents the subject in the way that we find most interesting. This is not to say that there aren't plenty of other cryptography textbooks with perfectly valid viewpoints, but they don't say what we wanted to say.
There is also a great deal of satisfaction in holding in one's hands a book that one has written, and it's great to receive positive feedback from readers. There's even satisfaction in receiving lists of errata, since it shows that someone cares enough to carefully read your book!
As a practical matter, as others have indicated, it's easiest to write a book after developing the material as a course and creating detailed lecture notes. But the road from lecture notes to polished publishable book is neither short nor straight.
Finally, since it seems apposite, I'll end with a link to an article that I recently wrote entitled: Rational points on, and the arithmetic of, elliptic curves: A tale of two books. It details some of the history behind the writing of two of my books, and is (freely) available at http://www.ams.org/journals/bull/0000-000-00/S0273-0979-2017-01542-X/S0273-0979-2017-01542-X.pdf