Presentation is loading. Please wait.

Presentation is loading. Please wait.

Assignment 3 A Client/Server Application: Chatroom.

Similar presentations

Presentation on theme: "Assignment 3 A Client/Server Application: Chatroom."— Presentation transcript:

1 Assignment 3 A Client/Server Application: Chatroom

2 Socket  socket creates an endpoint for communication.  Two useful headers for socket programming:  #include

3 Description  Server:  supports at most 10 clients one time  Client:  will be asked for a hostname for the server e.g. “”  Will be asked for a username (alias)

4 Chatroom Behavior  Basic: client types a message and presses enter; server will receive the message and broadcasts to all clients  Special Commands:  If a client types /exit, /quit or /part, client exits; server prints a message that client(alias) has left  If a client presses Ctrl+C, a nice error message is printed and the user is asked to type /exit, /quit or /part  If Ctrl+C is pressed on the Server side, the server tells the clients that it will shut down in 10 seconds. Then the clients tries to exit (disconnect) gracefully and the server shuts down.

5 Server Side Implementation

6 Data Structures Server address:  sockaddr_in host={AF_INET, htons(SERVER_PORT)}  In the Internet address family, the SOCKADDR_IN structure is used by Windows Sockets to specify a local or remote endpoint address to which to connect a socket.  An important aspect about SERVER_PORT is that all ports bellow 1024 are reserved. You can set a port above 1024 and below 65535.  Make sure that the port number is not used by other users. htons(): convert host to network short Client address: sockaddr_in peer = {AF_INET}

7 Create New Socket socket() - creates an unbound socket in a communications domain, and return a file descriptor that can be used in later function calls that operate on sockets or return -1 on error. A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. socket(int domain, int type, int protocol)  domain -> communications domain in which a socket is to be created: AF_INET or AF_UNIX. (AF_INET is used for our application)  type -> type of socket to be created. (Stream or Datagram)  protocol -> 0 : use an unspecified default protocol  Example:  soc = socket(AF_INET, SOCK_STREAM, 0);

8 bind socket bind() – associate a socket with a port, returns -1 on error int bind(int socket, const struct sockaddr *address, socklen_t address_len);  socket -> file descriptor of the socket to be bound.  address -> points to a sockaddr structure containing the address to be bound to the socket.  address_len -> length of the sockaddr structure pointed to by the address argument.  Example:  Bind(soc, (sockaddr*)&host, sizeof(host))

9 listen for new connections  listen() –  listen for connection requests and declare a queue size for the incoming simultaneous connection requests. int listen(int socket, int backlog)  Backlog -> sets a limit for the number of simultaneous connection requests who are waiting to be connected. Example:  listen(soc, 4) -  only 4 simultaneous connection requests can be handled. However, there is no limit for the number of connections that can be made which arrive sporadically.

10 Accept a new connection accept() - accepts a new connection on a socket  int accept(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len);  Address  Either a null pointer, or a pointer to a sockaddr structure where the address of the connecting socket shall be returned  address_len  Points to a socklen_t structure which on input specifies the length of the supplied sockaddr structure, and on output specifies the length of the stored address.  Example:  netSock = accept(soc, (sockaddr*)&peer, (socklen_t*)&peerlen); create a separate thread for each client connection Each client is handled using a seperate thread. pthread_create(&myThread, NULL, ClientHandler, &var);

11 steps in Server so far … socket() bind() listen() accept()  Assign an unique ID (1 to n) to each client using a shared array. Use Mutex lock/unlock while accessing this array. pthread_create() for each client:  handle read/write operations in thread body

12 ClientHandler Declare arrays for  read buffer, write buffer, userName Each Client will send a message containing its username(alias) first Write to the client using write buffer a welcome message:  e.g: strncpy(writeBuf, "Welcome ", 8) Print to all clients that a new user (Client) has entered the chat room The data that clients send is stored in read buffer Print read buffer data on server’s terminal as well as the client terminals (except for thisClient) If a special message (/exit, /quit or /part) is received from a client  then print a goodbye message and remove this client from the client array

13 Client Side Implementation

14 Data Stuctures & functions Client structure:  members – clientName  clientId // ‘0’ initially Server’s address Info:  struct sockaddr_in host = {AF_INET, htons(SERVER_PORT)}; Buffer – an array used for writing data void* EchoHandler(void * soc) – thread handler function void signalhandler(int sig) – if Ctrl-C is pressed for client, it won’t let it exit, rather print message asking to type “/exit” or “/part” or “/quit”

15 Connection to Server Prompt to enter the hostname to which user wants to connect. Use gethostbyname() to save the hostname  gethostbyname() is used to get its IP address and store it in a struct in_addr  Takes a string (like or as  e.g: hp = gethostbyname(argv[1]) Print an error message if return value is NULL (hostname does not exist)  bcopy(s1, s2) copies n bytes from the area pointed to by s1 to the area pointed to by s2.  Example: bcopy(hp->h_addr_list[0], (char*)&peer.sin_addr, hp->h_length)  Where host address is saved by gethostbyname() in hp. Then, enter the client’s username (alias) as required

16 create a socket and connect to server  socket() - create a client socket  Connect() - connect to server, return -1 on error  int connect(int socket, const struct sockaddr *address, socklen_t address_len);  socket  Specifies the file descriptor associated with the socket.  address  Points to a sockaddr structure containing the peer address. The length and format of the address depends on the address family of the socket.  address_len  Specifies the length of the sockaddr structure pointed to by the address argument. Create separate threads to handle read and write -A thread to accept user input and check for exit condition and write to the server -A thread for reading the messages from the server and printing it on user’s terminal -The thread handler will take care of different errors and special messages to be printed.

17 Ctrl+C sigHandler()  signal(SIGINT, signalhandler)  Ctrl-C will raise SIGINT  By default, SIGINT immediately terminates the process  In this assignment, you define your own SigHandler as below:  Signalhandler(int sig) { If Ctrl-C is pressed by the client, it should print a nice error message and ask the user to type /exit, /quit or /part instead. }

18 Thread Handling  Create Thread  Method - pthread_create  It accepts a thread variable, a thread attribute, a start routine function, and an optional argument. To use default thread attributes, pass NULL as the second argument.  Example if ( pthread_create( &thread, NULL, fromServer, &client_info)) { perror( "Show Error"); exit( 1 ); }

19 Thread Handling  Exit Thread  Method - pthread_exit  This method is called after a thread has completed its work and is no longer required to exist.  Example pthread_exit(thread);

20  Example if ( pthread_create( &read_thrd, NULL, fromServer, &client_info)) { perror( "Show Error"); exit( 1 ); } if ( pthread_create( &write_thrd, NULL, fromUser, &client_info) { perror( "Show Error"); exit( 1 ); } pthread_join(read_thrd, NULL); pthread_join(write_thrd, NULL); pthread_exit(read_thrd); pthread_exit(write_thrd);. Thread Handling

21 End of Session

Download ppt "Assignment 3 A Client/Server Application: Chatroom."

Similar presentations

Ads by Google