Download presentation
Presentation is loading. Please wait.
Published byBarnard Ray Modified over 9 years ago
1
http://cs.mst.edu Assignment 3 A Client/Server Application: Chatroom
2
http://cs.mst.edu Socket socket creates an endpoint for communication. Two useful headers for socket programming: #include
3
http://cs.mst.edu Description Server: supports at most 10 clients one time Client: will be asked for a hostname for the server e.g. “rc01xcs213.managed.mst.edu” Will be asked for a username (alias)
4
http://cs.mst.edu 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
http://cs.mst.edu Server Side Implementation
6
http://cs.mst.edu 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
http://cs.mst.edu 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
http://cs.mst.edu 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
http://cs.mst.edu 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
http://cs.mst.edu 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
http://cs.mst.edu 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
http://cs.mst.edu 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
http://cs.mst.edu Client Side Implementation
14
http://cs.mst.edu 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
http://cs.mst.edu 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 www.yahoo.com or rc01xcs213.managed.mst.edu) as parameter.www.yahoo.com 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
http://cs.mst.edu 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
http://cs.mst.edu 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
http://cs.mst.edu 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
http://cs.mst.edu 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
http://cs.mst.edu 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
http://cs.mst.edu End of Session
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.