How do hackers take advantage of open ports as a vector for an attack?
Services listen to ports. Web servers (a service) listen to port 80, but that's just a standard, not a hard rule. You could configure any service to listen on any port. It's not about 'special packets' it's about 'dialing the right port number' to get the service you want.
If your pseudo program has a vulnerability, then it can be attacked on the port it is assigned to. You can't attack a program on ports it is not listening to. If you try to attack it on another port (like port 80 in your example), your program will not be reached.
Your last question, then, is a little strange: "Why can't a hacker try to craft a TCP packet with a malicious string, encapsulate it inside the HTTP packet and therefore attack the web server?" That IS what hackers do. But they target the port of the service they want to hit. But maybe you can refine that question based on the information I have provided.
So, why close ports? Because you want to reduce the number of potentially vulnerable services that you expose to the Internet.
"Blocking ports" is just an approximate way of stating what we really want to do, which is blocking access to some services.
A freshly-installed operating system often has a number of things running automatically, some of which being services which have a network part. Any network-exploitable vulnerability in such a service is a potential access door for an attacker. However, it is rarely relevant that all such services be accessible by everybody throughout the wide Internet. For instance, for a machine which is supposed to be a Web server, it is normal that anybody on Earth may try to access the specific "Web" service (that's its functionality), and it is usual that the SSH service is also open (so that the server administrator may administrate the server); there is no use, however, that file-sharing services for that server be also widely open.
Blocking access to a given port can be done on the firewall and is considered more time-efficient than trying to convince the OS not to run a given service, and to refrain from relaunching it, or inventing new services, at the occasion of a software update. So it is customary to block all ports except those which are known to correspond to services which should be accessible worldwide (e.g. 80 and 22, for Web and SSH, respectively).