The Socket class in Java provides a way to create client-side sockets that can connect to a server on a given IP address and port number. Once the connection is established, the client and server can exchange data through the socket.
Here's an example Java program that creates a server socket and sends the string "hello" to the client:
import java.io.*;
public class Server {
public static void main(String[] args) {
try {
// create a server socket object
ServerSocket serverSocket = new ServerSocket(8080);
// wait for a client to connect
Socket clientSocket = serverSocket.accept();
// create an output stream to send data to the client
OutputStream os = clientSocket.getOutputStream();
PrintWriter writer = new PrintWriter(os, true);
// send the string "hello" to the client
writer.println("hello");
// close the output stream, socket, and server socket
writer.close();
os.close();
clientSocket.close();
serverSocket.close();
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
This program creates a ServerSocket object on port 8080 and waits for a client to connect. Once a client connects, it creates an output stream to send data to the client and sends the string "hello" using a PrintWriter. Finally, it closes the output stream, client socket, and server socket.
Note that in order to run this program, there must be a client running that is able to receive and process the data sent by the server.
No comments:
Post a Comment
If you have any doubts, please let me know