Download presentation
Presentation is loading. Please wait.
1
IE
2
Firefox
3
Persistent connections
HTTP/1.1 傳完之後不會自動斷線。 HTTP/1.0 才會自動斷線。
4
TCP Client-Server Interaction
TCP Server socket() bind() TCP Client listen() socket() accept() connection establishment connect() data request read()/recv() write()/send() data reply write()/send() read()/recv() end-of-file notification read() close() close() from UNIX Network Programming Volume 1, figure 4.1
5
Include Headers #include <sys/socket.h>
#include <netinet/in.h> #include <unistd.h> #include <netdb.h>
6
Create a socket // declare a socket file descriptor int listenfd;
listenfd = socket( AF_INET, SOCK_STREAM, 0 );
7
Bind a socket to an address
// declare a int for bind()’s result int bindres; // declare a structure for address struct sockaddr_in proxyaddr; // initialize the structure memset(&proxyaddr, 0, sizeof(proxyaddr)); proxyaddr.sin_family = AF_INET; proxyaddr.sin_addr.s_addr = htonl( INADDR_ANY ); proxyaddr.sin_port = htons( 3128 ); //bind listenfd to bindres = bind( listenfd, (struct sockaddr *)&proxyaddr, sizeof( proxyaddr ));
8
Listen to the socket & Accept when someone connect
listen( listenfd, 5000 ); while(1) { connfd = accept( listenfd, (struct sockaddr *)NULL, NULL ); // do things like read and write with connfd doit(); close(connfd); } close(listenfd);
9
What we have to do doit() { // 1. read request from the client
// 2. parse request // 3. build another connection to the server // 4. send request to the server // 5. read response from the server // 6. close connection with the server // 7. parse response // 8. send response to the client }
10
How to read? Use read() Use recv() int fd = socket(…);
read( fd, buf, strlen( buf ) ); Use recv() recv( fd, buf, strlen( buf ), 0 ); int fd = socket(…); char buf[1024]; or char *buf;
11
How to write? Use write() Use send() int fd = socket(…);
write( fd, buf, strlen( buf ) ); Use send() send( fd, buf, strlen( buf ), 0 ); int fd = socket(…); char buf[1024]; or char *buf;
12
How to connect to the server?
int servfd = socket(…); connect( servfd, ( struct sockaddr * ) &servaddr, sizeof( servaddr ) );
13
HTTP Request GET http://network2006.csie.org/index.html HTTP/1.0
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */* Accept-Language: zh-tw User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; (R1 1.3); .NET CLR ) Host: network2006.csie.org Proxy-Connection: Keep-Alive
14
HTTP Response HTTP/1.0 200 OK Connection: close
Content-Type: text/html ETag: " " Accept-Ranges: bytes Last-Modified: Fri, 17 Mar :23:08 GMT Content-Length: 80 Date: Wed, 22 Mar :42:47 GMT Server: lighttpd/1.4.10 Body …………………….
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.