UDP Server
When a client wants to interact with a UDP server, a UDP socket is created on the client's machine. When a client sends a packet to UDP server it attaches a destination address which consists of UDP Server's IP Address & Port number to the packet. Moreover, Client's IP address, as well as the port number of the client socket, is also attached to the packet.
Similarly, UDP Server also creates a socket on his machine. The UDP server is always listening at the port number assigned to the socket. When any client sends a packet to the server's port number at the IP address of the server that packet will be directed to the server’s socket. When a packet arrives at the server’s socket, the packet’s data along with the packet's source address(Client’s IP & Port Number) is stored. With this source address information, the server knows where it should direct its reply. Server processes the client’s packet & sends the reply packet to client using the client’s IP & Port number which is already saved at the server. After the server sends the packet, the server remains listening at the port number assigned to the socket, waiting for another UDP Packet to arrive from any client running on any host.
TCP Server
When a client wants to interact with a TCP server, a TCP socket (clientSocket) is created on the client's machine. Before the client can send data to the server (or vice versa) using a TCP socket, a TCP connection must first be established between the client & server.
TCP Server creates a socket (serverSocket) & associates port number (serverPort) with this socket (serverSocket). The server waits & listens for clients on this socket (serverSocket). When a server receives the requests from a client at serverSocket, Server creates a new socket called connectionSocket, dedicated to this particular client. The client & server then complete the handshaking, creating a TCP connection between the client’s clientSocket & the server’s connectionSocket. With the TCP connection established, the client & server can now send data to each other over the connection. Once the data transfer is completed between client & server, server closes the connectionSocket dedicated to this particular client. But since serverSocket remains open, another client can also send requests to the server.