Transmission and Programming | Socket Programming: TCP | Alison
Loading

Module 1: Transmission and Programming

Nota de Estudos
Study Reminders
Support
Text Version

Socket Programming: TCP

Set your study reminders

We will email you at these times to remind you to study.
  • Monday

    -

    7am

    +

    Tuesday

    -

    7am

    +

    Wednesday

    -

    7am

    +

    Thursday

    -

    7am

    +

    Friday

    -

    7am

    +

    Saturday

    -

    7am

    +

    Sunday

    -

    7am

    +

Socket Programming: TCP
So, welcome back to the course on Computer Network and Internet Protocols and in thelast class, we are discussing about socket programming in today’s lecture, we will againcontinue with the socket programming in details. So, in the last class we have looked intothe UDP socket, we have looked into the basic of socket programming along with theUDP server and the UDP client in details that how you can use this concept of socdatagram under datagram socket to transfer data receive data using UDP protocol. So,today we look into how you can do the same thing using TCP protocol and we look intodifferent variants of TCP server.(Refer Slide Time: 00:57)(Refer Slide Time: 01:11)So, first let us look into the demo of demo about the TCP server and a TCP client. So,first we look into this TCP server the source of the TCP server in details, well so do notget confused to it end arrow. So, these are C program do not get with this end arrow andthis dot just a formatting we have used for our clarity of writing the code. So, this is yourC code well.(Refer Slide Time: 01:35)So, we have this network related header, which are being included followed by the mainfunction so, in the main function similar to the UDP1, UDP server that we havediscussed, we are declaring a the server address first, server address variable of typestruck sockaddr in and file descriptor to store the socket id that will be created and this isthe syntax that how you should use the code, we are taking the code number from thecommand line argument and then we are taking the port number from command lineargument and we are creating the socket by this socket system call.So, this socket system call similar to the earlier case it will take a finite as the protocolfamily, but the socket type is now SOCK STREAM in state of SOCK DGRAM. So, andfinally, it is a protocol field is 0 and as I have asked you earlier that try to explore thatwhy we mostly use protocol family protocol type as 0.Now if the socket is not created successfully some error message that is getting printedand after that we are initializing the server address field the server address familyprotocol family we are setting it as AF INET, because we are going to use the IPv4address followed by the server address or server address we are taking it asINADDR_ANY. So, this INADDR ANY will help us to take the address of the local hostthen, we are providing the port number which are have taken from the concept.So, we have initialized the sever address. So, once you have initialized the serveraddress, you have to bind it with the socket. So, we are making a bind system call. So,the bind system call may fail sometime because, if you are going to use the same portnumber which is being used by another application, there are other reasons where a bindcall may fail. So if the bind fails, we are having a error message that it is fail to bind thatotherwise, the bind was successful. And the bind is taking the format as we havediscussed earlier the socket file descriptor the address of the server and the size of theserver address variable.Now we are making a listen call, the listen call here we are providing the socket andsocket file descriptor and we have specified 5 as the maximum number of connectionthat can be backlogged in the listen call. So this concept of backlog connection is that,the server can handle one client at a time. So, whenever it is taking the connection oneclient, during that time multiple client can again try simultaneously, just think of thescenario of a web server, where thousands of request are coming to the web server persecond.So, during that time when the server is busy in executing this say the listen call for oneconnection during that time the other connection will get backlog. Now, in side the loop, what we are doing, we are making the accept called at the serverside, now TCP is a connection oriented service that is, why you have to make the connectcall from the client side and accept call from the server side to initiate the connection,which will utilize the three way handshaking of the TCP protocol. So, after we aremaking the accept call the accept call, we are passing the parameter as the socket filedescriptor, the address of the client and a length of the client address if there is an error.So, all this function if there is an error, they return some negative number. So, that is whyyou can check the return value if it is less than 0; that means certain error has occurred.Ok. So, after that once it is accepted the connection, we are printing that we havereceived a new connection from the client address, we are specifying the client addressand the client port. So, from that particular client address and the client port a newconnection has been received and after that we are having a loop, where we are receivingthe data from the new socket that has been created.Now, here also while you are making the accept call, in the accept call, it returns new filedescriptor and this new file descriptor will initiate this end to end connection, betweenserver and the client. So, it returns a new socket descriptor that we will used in the insending or the receiving data, which is specific to a pipe or specific to a socket between asever and the corresponding client.Now, if receiveLen is equal to equal to 0; that means, you are not receiving any datafrom the client. So, you can close this particular connection. Otherwise you get the dataand put in that data that you are receiving at the server side and after that we are actuallywhatever data we have received, we are requiring same data to the client by using thissame function ok. So, you have received the data, which is stored in the received buffersame data is decode back to the to the client side.Ok, at the client side, things are pretty similar on we are declaring the socket we arecreating a new socket and after creating the new socket, we are getting the here in theclient side, we are getting the server IP or the server host name and the port from thecommand line argument. So, we are using that command line argument to create theserver address.So, it initializes the connection to the server using the TCP three way handshakingprocedure. Now, after that after the connect system call has made, you have initiated theconnection to the server then, you make the call to the send function, the send function tosend the data. So, we are creating a message called hello there this particular message,we are sending to the server and as you have seen in the server code that the server willactually go back that particular thing to the client.So, after you are sending that you are receiving the message. So, we are declaring abuffer as a character array, we will get the data in the form of a character array or astring. So, we are declaring that buffer for that and after that we are making a receivecall, this receive call over that socket file descriptor that will get the data from the clientside.So from the server side so as you have seen in the server code, the server will actually goback the data that you are sending so, here you are sending this hello there function,same hello there function will be got back. So, you will receive that data and afterreceiving that data you print that particular data at the concept. So, that is the code for theclient side.Now, let us compile and run this two things. So, first let us compile TCP server andcompile TCP client. So, first we will run the server. So, we need to specify the portaddress. So, we are giving port address as 2444, those server will now the server isrunning there. So, once the server is running there from the client side, we can give sothe server is running in my machine.So, I am giving the server host name as local host and the corresponding server port that,we have used here 2444. So, it has received the message and at the server side you cansee that, it has received a new connection from the local machine the IP is 127.0.0.1 anda port of 47676. So, it has received this hello there message, it has got it back and theclient has received that message.So, here you will see that this connections. So, here we are making a while loop andinside this while loop, we are accepting the connection.So, how this entire thing will work if multiple client equation are coming simultaneouslythen, one client will be taken that that connection will be taken that will get executed.Then the next client will be taken, that will get executed, then the third client will betaken, that will get executed and that way this entire thing will go on. I will suggest you to look into this process concept in operating system and look into it indetails. So, we will use this concept of process in the operating system to look into thisimplementation of concurrent servers at the parallel servers. So, as we have lookedearlier that you are creating multiple such connections.Now, if multiple clients are trying to connect to the server simultaneously, then how willyou handle that thing. So, one ways to handle it is using the iterative server, but as wehave seen that the iterative server may not be very useful. So, we implement the parallelserver using this concept of multiple processes in operating system.
Socket Programming: TCP - Part 2
So the idea is something like this you have a server process, which is having the parentsocket then, you can make a fork system call. So, in operative system, this fork systemcall creates a child process. So what you can do that once you are accepting a connectionthen you can make this fork system call to create a child process, which will actuallyhandle the data transmission and data reception from that particular child connection.If you are not doing that, if you are doing it in the earlier way that we are doing insidethe while loop in the form of iterative server, then the time until a particular server iskeep on sending and receiving data, it is not closing the connection up to that point theconnection will remain blocked. So, the server will not be able to handle the secondconnection until the first connection is complete.So, that is why the idea is that, whenever a new connection is coming, you make a forksystem call and after making a fork system call have a child process, that child processthat is the part of the server process, but that will create a child socket it will. So, wehave seen that after you are making an accept call at the server site, it returns a newsocket identifier, which is used to send or receive data to the client.So, you pass that particular new socket file descriptor to the child socket, which willhandle data transmission and reception in parallel. So, the broad idea here is that you getall the connections one after another, but do not wait for the send and a receivefunctionality of our individual connections and keep other connections in the waitingqueue. So, you create a child process and that child process will or we call it as a childsocket, that will handle the send and a receive data functionalities of individual clientrequest that you are getting.(Refer Slide Time: 18:32)So, that was our implementation of the iterative server that we have done, we have awhile loop, inside the while loop you are making a accept call then, you have the sendand receive and it is inefficient because until you are complete that send and a receivefunctionalities, you will not be able to come out of that and get or make the accept callagain to accept the new incoming connection.So, if you look into that how iterative server works that the listen call it sets a flag that,the socket is in the listening state and set the maximum number of backlog connectionsthat you have seen earlier then, the accept call it blocks a receiving socket, until a newconnection comes in the connection queue and it is accepted. So, this accept call is ablocking call. So, the system will keep on waiting here until, you are making a connectcall from the client side. So it is a blocking call.Now, once this new connection is accepted, then the new socket file descriptor say, theconnection fd it is written, which is used to read and write data or to send and receivedata to the connective socket. Now all other connection, which comes in this duration arebacklogged in the connection queue, because the process is busy inside this while loop tosend and receive data. Now, we extend this iterative sever to a concurrent server. So, our idea is that the parallelprocessing of each incoming socket, so that the accept call is executed more frequently.So, what we do here? Here you see that after we are making this accept call, which isreturning the new socket file descriptor then, we have successfully accepted a clientconnection then we making a fork system call. So, this fork system call at the parentprocess, it returns the idea of the child process and at the child process it returns 0.So, whenever you are making this fork system call and if the fork system call is returning0; that means, you are inside the child process. Now this child process, what it does? Itcloses the original socket the server socket and it will use this new socket fd that you gotto send and receive data. So, you close the old socket since all communication will bethrough the new socket and then you initialize the buffer, copy the message to it, send ordo the receipt whatever you want to do.Now, what will happen here that whatever is there inside the fork system call, inside thisfork block in this if block that will executed get executed in parallel. So, in the parentprocess the parent process will not so for the parent process, this will receive return false,because parent the parent process fork returns the ID of the child process and in the childprocess fork returns 0.So, in the parent process you will return back and the parent process will again comehere and make the next accept call. So, the parent process now do not need to wait forthis send and receive functionalities, which will be handled by a child process.Now, let us look into the demo of this one. So, here we do not make any change in theclient implementation. The client implementation remains as it was earlier, we will onlymake change at the server implementation. So, at the server implementation, so thechange that, we have made the entire code is similar if you look into that we aredeclaring this server address, followed by a socket call then initializing the addresses atthe server address field, making a bind call, making a listen call to broadcast the or not toactually broadcast this may not be a correct term to announce the port where the sever isactually listening and after that making that set sock opt call as earlier and then insidethis while loop, where you are accepting accepting the connection we are acceptingaccepting a new connection and it is going to this child fd we are creating a new filedescriptor.After that you see we are making a fork call. So, you look into this statement in forreturn equal to fork. So, we are making a fork call which will create a child process, nowI will suggest you to look into this operating system concept in details, we do not havescope to discuss that, the idea here is that whenever you are making a fork call this entirecode will be copied to the child process as well. So, the child process what it will do? Inthe child process, the fork call will return a 0 and in the parent process the fork call willreturn the ID of the child process.So, inside the child process this part of the code will get executed. Now you see this thesecond while loop that we had which actually deals with sending and receiving data, it isinside only the child process. So, it is inside this if block here we are making this receivecall and a send call.And we are having that handling in parallel at the sever side. So, in the server side thisparticular if block will not get executed, because in the server in the parent side, parentsocket this will not get executed, because the parent socket will return the ID of thechild. So, it will be not equal to 0.So, this part will only execute at the child process. So the child process is now dealingwith sending and receiving of the data, but the parent process can come out of that, theparent process is not getting blocked in this second while loop, it can directly come outand accept the next connection.So, we will possibly not get a feel of this parallel execution, but what is happening there.A new child process gets created and it handles this individual request that we aresending here.Now in this particular case, what may happen that we do not have any central server tocontrol the chat message delivery, every user runs it is own chat server; that means, itruns the TCP server for incoming come incoming connections and messages, now inUNIX, it maintains every connection as a file descriptor that we have already seen.Now, at that time in a chat server you have a typical requirement that you need to alsoread data from standard input. So, you need to type something. So, when you arereceiving a message during that time say, you are typing something. So ok for that we use this concept at the select system call, which is again an operatingsystem level system call.So the select system call, it selects from multiple file descriptor, which is a concurrentway to handle multiple file descriptor simultaneously even from a single process. So, youcan get the data from the socket, which is one of the file descriptor as well as thekeyboard file descriptor simultaneously.Now, what we have seen that, what happens in an iterative server implementation that wehave done earlier that the accept call is blocked until you have completed the read andthe write calls. Now what if you do multiple read and write activities after accepting anincoming connection, that the other connections are blocked and waiting for theconnection queue, they may get starved. Now select is the way to break this blocking.So, one way to break the blocking is using this parallel implementation another way todo that thing is to use the select system call. The advantage with this select system call isthat, you do not need to create multiple child processes, now no you do not need to worryabout the zombies. So, child processes has always a problem that if you are if sometimethe parent process get killed or the parent process stops, then the child process becomezombie. So, with the select system call you do not need to worry about this zombie. So,you can possibly manage resources more efficiently
Socket Programming: TCP -Part 3
So, this selects system call it is nothing but a multiplexer.
So, what happens that you have multiple file descriptors, you have certain signals and thetime out and out of this multiple file descriptor, it selects one of the file descriptor. So, itfinds out that among this file descriptor which one is currently active and it select thatparticular file descriptor.So, here is the format of the select system call, in the select system call you are providingthe number of file descriptor, it is the highest number of file descriptor in any of the threesets plus 1, we have three different sets of file descriptor, the read file descriptor to readsomething as an input, the write file descriptor to write something at the output andexcept file descriptor to handle the exceptions.So, this file descriptors are a kind of structure called fd set and we have a timeout value.So, the timeout value is that if you are not getting anything from this file descriptor forthis timeout value. So, it will come out of the things.So, it is actually providing you a synchronous I/O multiplexing over asynchronous input.So, as we have mentioned earlier that your input can be asynchronous, you can get amessage over the socket while you are doing the typing, but it provides you amultiplexing to select either the keyboard or the socket at one time distance.So, you have three different file descriptor that each file descriptor will be watched to seeif characters become available for reading, the write file descriptor will be watched to seeif the spaces available for write and the exceptional file descriptor will be watched forexceptional condition.Now we have a timeout value, the interval that select should block waiting for a filedescriptor to become ready, now the select call remain block either the file descriptorbecomes ready or the call is interrupted by a signal handler or a timeout expires. So, inany of the cases it comes out of the select. So, whenever one of the file descriptorbecomes ready it comes out of the select call, if that particular call is interrupted by someother signals or the timeout happens. So, this is the procedure to set the timeout youprovide the value in the form of second and microseconds.(Refer Slide Time: 32:59)Now, how do you pass the file descriptor to select? So for that what we do, we firstinitialize the file descriptor set fd set, which is a bitmap of fix size with this fd 0, then wemake the call to fd set. So, if this fd set selects a file descriptor say, my socket that I havedefined and the corresponding the file descriptor, which where the socket is gettingadded. So, this particular bit corresponds to this socket file descriptor that will get set;that means, some data is available there.(Refer Slide Time: 33:42)Ok then you make the select call so, how select works? So, it looks over all the filedescriptor for every file descriptor it calls the file descriptor poll method. So, this pollmethod is to check that whether something is available to or some event is waiting onthat file descriptor. So, it will add the caller to that file descriptor wait queue and return,which events currently apply to that file descriptor whether it is file descriptor isreadable.If it is a read file descriptor whether it is writable, if it is a write file descriptor or someexception has happened. Now if any of the file descriptor matches the condition that theuser was looking for read, write or exception, then the select will simply writtenimmediately, after updating the appropriate file descriptor set that the user passed and ifnot the select will go to sleep for the timeout value once, the timeout occurs it will comeout of that select call.(Refer Slide Time: 34:43)And if some other events happen within that timeout event, it will made this FD set andcome out of that. And during that interval if an interesting event happens to any of thefile descriptor that select is waiting on that file descriptor will notify its wait queue. So,this will cause that thread sleeping inside the select wakeup and it will repeat the aboveloop and see which of the file descriptor are now ready to be returned to the user.Now, the return value of the select we have three values if it is minus 1 means some errorhas encountered. 0 means that the timeout has happened and greater than 0 means, thatthat the number of sockets that has the event pending like read write or exception. So, forhow many sockets that event is pending, whether you are going to read or write orhaving certain exception.(Refer Slide Time: 35:23)So, after select returns you can use the function called FD set to test, whether a filedescriptor is a part of that set. So, you can check whether a file descriptor has been set ornot if the file descriptor has sat set; that means, you have something to read, if it is a readfile descriptor or you have something to write if it is a write file descriptor.(Refer Slide Time: 35:55)So, let us look into a code which uses this select call. We will use the same TCP serverimplementation with this select.(Refer Slide Time: 36:18)So, the base part of the code is same as earlier we are declaring the server address, thebind call, the listen call at the server side the set sock opt call and after that we aredeclaring the file descriptor. So, here we are declaring that we can have a maximum of16 different file descriptor and this fd len returns, that how many are how many such filedescriptor are currently set or currently active.So, we are declaring the set of file descriptor and the maximum file descriptor which isequal to the current socket file descriptor. Now inside this while loop, we first initializethe file descriptor, we are here only going to use the read file descriptor because we aregoing to read data from the socket and we are setting through this fd set call, we aresetting the read file descriptor corresponds to the socket that we have defined or thesocket where the server is actually listening.Now, we are looping over the available file descriptor. So, here the idea is that wheneverwe are getting a new connection, we are adding it a inside the file descriptor inside thatfile descriptor set.(Refer Slide Time: 37:25)After that we are making a select call. So, as we have seen earlier that there we are notgiving any timeout value, because we are not giving any timeout value. So, it will keepon waiting for infinite duration, whenever some event will occur then only it will comeout. So, we are initializing with this read file descriptors.So whenever a new connection will come, it will come to this read file descriptorthrough this loop and then it will keep on waiting here, when some event will occur thatold function will get triggered and that old function will return, whether certain event isthere in the read file descriptors certain event means, whether that particular socket isready to read the data.And after that if select returns; that means, some socket is ready for reading the data thenyou check using fd set, whether that particular socket is ready to read the data if thatsocket is ready to read the data then, you make a accept call, accept call to accept thatparticular connection that means, some connection is waiting you accept that connectionand after doing that, the way we are closing the child file descriptor and then add thatparticular thing to that file descriptor loop.(Refer Slide Time: 38:52)Then in this fd set you loop over all the file descriptor that you have been added.So, if that received len is equal to equal to 0; that means, you are not receiving any data.So, you close that file descriptor and clear it from your file descriptor set.So, this is all about our discussion on TCP server, I was quite fast in describing the thingswith the assumption that you have a basic knowledge of C programming and operatingsystem, we will share all the codes with you and I will suggest you to browse the codeand look into the tutorials that we have shared.And if you have any doubt or anything feel free to post the questions in the forum. So,with this particular socket programming, you can develop your own applications you caneven implement the chat server application that we are talking about. So, I will suggestyou to look into that and implement multiple such applications on your own with thehelp of this different variance of socket programming.So, thank you all for attending this class; from the next class onwards, we will go foragain the theoretical aspects of the TCP/IP protocol stack.So thank you all for attending this class.

Notification
Você recebeu uma nova notificação
Clique aqui para visualizar todos eles