Project 2: Socket Programming
Overview Sockets Working with sockets Client-Server example Project 1 Hints
Socket What is socket? –An abstraction through which an application may send and receive data –Different types Stream sockets we will use for our project Datagram sockets
Berkeley Sockets The socket primitives for TCP.
Working with Sockets Sender creates a new socket Attach a local address to the socket: binding operation Receiver listens, announces willingness to accept socket connection with a queue size announcement Block the caller/receiver until a connection establishment attempt arrives Sender and Receiver are connected Send data (by sender) and receive data (by receiver) When done sending and receiving data explicitly close the connection
A Client-Server Example TCP Client –Create a TCP socket sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); –Establish a connection to the server connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr) –Communicate with server send(sock, msg, stringLen, 0) recv(sock, buffer, RCVBUFSIZE - 1, 0) –Close the connection close(sock)
A Client-Server Example (cont.) TCP Server –Create a TCP socket servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) –Assign a port number to the socket bind(servSock, (struct sockaddr *) &servAddr, sizeof(servAddr) –Tell the system to allow connections for that port listen(servSock, MAXPENDING) –Accept new client connection clntSock = accept(servSock, (struct sockaddr *) &clntAddr, &clntLen) –Communicate (send, recv) using clntSock –Close client connection (close clntSock )
Project 2 Requirements –Implement a chat program that incorporates both client and server functionalities Server client
Illustration ssh-server% chat –connect // connect to the server in in port –accept connection from // accept a connection from the client in –receive HELLO from // get data message from the client in –receive HELLO from // get data message from the server in –send HELLO// send message to the server in –send HELLO// send message to the client in
Notes for Our Project Need for “ multiple ” requests –Server needs to receive New client connection attempts Connected clients ’ data User ’ s input (standard input) –Client needs to receive Server ’ s data User ’ s input (standard input)
Notes for Our Project (cont.) Solution for “ multiple ” requests –Using “ select ” -- a single process handles multiple requests –select() works by blocking until something happens on a file descriptor (e.g., a socket) –Usage ( Fill up a fd_set structure with the file descriptors you want to know when data comes in on. Call select() and block until something happens Once select() returns, check to see if any of your file descriptors was the reason you woke up, then do the following operation Repeat this process
Submission Details Submit the electronic copy Set up appointment with the instructor/TA to demonstrate the functionality