0% found this document useful (0 votes)
1 views2 pages

Java Networking Programs

Uploaded by

khaparderahil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views2 pages

Java Networking Programs

Uploaded by

khaparderahil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

1. URLDetails.

java
import java.net.*;

public class URLDetails {


public static void main(String[] args) {
try {
URL url = new URL("http://www.msbte.org.in");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("File: " + url.getFile());
} catch (MalformedURLException e) {
System.out.println("Invalid URL");
}
}
}

2. IPFinder.java
import java.net.*;
import java.util.Scanner;

public class IPFinder {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter hostname: ");
String host = scanner.nextLine();
try {
InetAddress inet = InetAddress.getByName(host);
System.out.println("IP Address: " + inet.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Host not found");
}
}
}

3. ChatServer.java
import java.io.*;
import java.net.*;

public class ChatServer {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5000);
Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String msg;
while (true) {
msg = reader.readLine();
if (msg.equalsIgnoreCase("exit")) break;
System.out.println("Client: " + msg);
System.out.print("Server: ");
writer.println(console.readLine());
}
socket.close();
serverSocket.close();
}
}

4. ChatClient.java
import java.io.*;
import java.net.*;

public class ChatClient {


public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 5000);
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String msg;
while (true) {
System.out.print("Client: ");
msg = console.readLine();
writer.println(msg);
if (msg.equalsIgnoreCase("exit")) break;
System.out.println("Server: " + reader.readLine());
}
socket.close();
}
}

You might also like