This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Thursday, March 9, 2023

Define socket. What are the use of TCP and UDP socket? Write a TCP socket program to send "Hello server" text to the remote machine listening on 9999 port and having 192.168.10.20 IP address.

 A socket is a communication endpoint that allows two-way communication between two processes over a network. Sockets can be used for communication between processes running on the same machine or on different machines connected over a network.

TCP and UDP are two different transport protocols used over the internet. TCP (Transmission Control Protocol) is a reliable, connection-oriented protocol that provides ordered, error-checked data delivery. UDP (User Datagram Protocol) is a connectionless protocol that provides fast, unreliable data delivery without any guarantees of data integrity.

TCP sockets are typically used for applications that require reliable, ordered data delivery, such as web browsing, email, and file transfer. UDP sockets, on the other hand, are typically used for applications that require fast, lightweight data transmission, such as online gaming and video streaming.

Here is an example TCP socket program in Java that sends the "Hello server" message to a remote machine with IP address 192.168.10.20 and port 9999:

import java.net.*;
import java.io.*;
public class Client {
    public static void main(String[] args) throws IOException {
        String serverName = "192.168.10.20";
        int port = 9999;
        try {
            Socket client = new Socket(serverName, port);
            OutputStream outToServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);
            out.writeUTF("Hello server");
            InputStream inFromServer = client.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);
            System.out.println("Server says " + in.readUTF());
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this program, we create a TCP socket by specifying the IP address and port number of the remote machine using the Socket class. We then use the DataOutputStream class to send the "Hello server" message to the server, and use the DataInputStream class to read the response from the server. Finally, we close the socket using the close() method.

Note that this program assumes that there is a server running on the remote machine that is listening on port 9999 and will respond to the "Hello server" message.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget