Here's a **complete Java solution** for connecting to a server via **IP (Socket)** or **HTTP**, with the ability to **review and edit data after connecting**:
---
## **1. IP-Based Socket Connection (TCP) with Data Review**
### (Best for real-time apps like games, chat)
```java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class SocketClientWithReview {
public static void main(String[] args) {
String serverIP = "127.0.0.1"; // Replace with server IP
int serverPort = 8080; // Replace with server port
try (Socket socket = new Socket(serverIP, serverPort);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Scanner scanner = new Scanner(System.in)) {
System.out.println("Connected to server!");
// Send initial message
out.println("Hello Server!");
// Receive and review server response
String response = in.readLine();
System.out.println("Server says: " + response);
// Allow user to edit and resend
System.out.print("Edit and send back (or 'exit' to quit): ");
String userInput = scanner.nextLine();
while (!userInput.equalsIgnoreCase("exit")) {
out.println(userInput); // Send edited data
response = in.readLine();
System.out.println("Server says: " + response);
System.out.print("Edit and send back (or 'exit' to quit): ");
userInput = scanner.nextLine();
}
} catch (IOException e) {
System.err.println("Connection error: " + e.getMessage());
}
}
}
```
#### **Key Features:**
✅ **Connects via IP & Port**
✅ **Allows reviewing server responses**
✅ **Editable input before sending again**
✅ **Type `exit` to disconnect**
---
## **2. HTTP Connection (URL) with Data Review**
### (Best for web APIs, REST services)
```java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class HttpClientWithReview {
public static void main(String[] args) {
String url = "http://www.example.com/api"; // Replace with your URL
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Connecting to: " + url);
// Initial GET request
String response = sendHttpGet(url);
System.out.println("Server response:\n" + response);
// Allow editing and resending
System.out.print("Edit data to POST (or 'exit' to quit): ");
String userInput = scanner.nextLine();
while (!userInput.equalsIgnoreCase("exit")) {
response = sendHttpPost(url, userInput);
System.out.println("Server response:\n" + response);
System.out.print("Edit data to POST (or 'exit' to quit): ");
userInput = scanner.nextLine();
}
} catch (IOException e) {
System.err.println("HTTP error: " + e.getMessage());
} finally {
scanner.close();
}
}
private static String sendHttpGet(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
return readResponse(conn);
}
private static String sendHttpPost(String url, String data) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(data.getBytes());
}
return readResponse(conn);
}
private static String readResponse(HttpURLConnection conn) throws IOException {
try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
response.append(line).append("\n");
}
return response.toString();
}
}
}
```
#### **Key Features:**
✅ **Connects via HTTP (GET/POST)**
✅ **Fetches and displays server data**
✅ **Editable input before sending again**
✅ **Type `exit` to quit**
---
## **How to Test These Programs**
### **For Socket (IP) Version:**
1. Run a **Java Socket Server** (or any TCP server like `nc -l 8080` on Linux/Mac).
2. Update `serverIP` and `port` in the client code.
3. Send and edit messages interactively.
### **For HTTP Version:**
1. Use a **real API** (like `https://jsonplaceholder.typicode.com/posts/1`) or a local web server.
2. Edit the `url` in the code.
3. Send GET/POST requests and modify data.
---
## **Which One Should You Use?**
| Feature | **IP (Socket)** | **HTTP** |
|---------|--------------|--------|
| **Best For** | Games, Chat, Real-time | Web APIs, REST Services |
| **Protocol** | TCP (Low Latency) | HTTP/HTTPS |
| **Data Format** | Raw (Custom) | JSON/XML/Text |
| **Security** | Manual (SSL/TLS) | Built-in HTTPS |
### **Recommendation:**
- **Need fast, real-time communication?** → Use **Sockets (IP)**.
- **Working with web services?** → Use **HTTP**.
Would you like a **server-side example** to test these clients? π
No comments:
Post a Comment