Graphics Programs Reference
In-Depth Information
The listen() call tells the socket to listen for incoming connections, and
a subsequent accept() call actually accepts an incoming connection. The
listen() function places all incoming connections into a backlog queue until an
accept() call accepts the connections. The last argument to the listen() call
sets the maximum size for the backlog queue.
while(1) { // Accept loop.
sin_size = sizeof(struct sockaddr_in);
new_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &sin_size);
if(new_sockfd == -1)
fatal("accepting connection");
printf("server: got connection from %s port %d\n",
inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
send(new_sockfd, "Hello, world!\n", 13, 0);
recv_length = recv(new_sockfd, &buffer, 1024, 0);
while(recv_length > 0) {
printf("RECV: %d bytes\n", recv_length);
dump(buffer, recv_length);
recv_length = recv(new_sockfd, &buffer, 1024, 0);
}
close(new_sockfd);
}
return 0;
}
Next is a loop that accepts incoming connections. The accept() function's
first two arguments should make sense immediately; the final argument is a
pointer to the size of the address structure. This is because the accept() func-
tion will write the connecting client's address information into the address
structure and the size of that structure into sin_size . For our purposes, the
size never changes, but to use the function we must obey the calling conven-
tion. The accept() function returns a new socket file descriptor for the accepted
connection. This way, the original socket file descriptor can continue to
be used for accepting new connections, while the new socket file descriptor
is used for communicating with the connected client.
After getting a connection, the program prints out a connection message,
using inet_ntoa() to convert the sin_addr address structure to a dotted-number
IP string and ntohs() to convert the byte order of the sin_port number.
The send() function sends the 13 bytes of the string Hello, world!\n to the
new socket that describes the new connection. The final argument for the
send() and recv() functions are flags, that for our purposes, will always be 0 .
Next is a loop that receives data from the connection and prints it out.
The recv() function is given a pointer to a buffer and a maximum length to
read from the socket. The function writes the data into the buffer passed to it
and returns the number of bytes it actually wrote. The loop will continue as
long as the recv() call continues to receive data.
Search WWH ::




Custom Search