Exam code:
import java.net.*;
import java.io.*;
public class CheckMail {
public static void main(String s[]) {
//
// CheckMail [mailServer] [user] [password]
//
try {
CheckMail t = new CheckMail();
int i = t.checkMyMail(s[0], s[1], s[2]);
if (i==0) {
System.out.println("No mail waiting.");
}
else {
System.out.println
("There " + (i==1?"is " :"are ") + i +
" message" +(i==1?"":"s")+ " waiting.");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private void send(BufferedWriter out, String s) throws IOException {
out.write(s+"\n");
out.flush();
}
private String receive(BufferedReader in) throws IOException {
return in.readLine();
}
private int checkMyMail
(String server, String user, String pass) throws IOException {
Socket s = new Socket(server, 110);
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
receive(in);
send(out, "USER " + user);
receive(in);
send(out, "PASS " + pass);
receive(in);
return getNumberOfMessages(in, out);
}
public int getNumberOfMessages
(BufferedReader in, BufferedWriter out) throws IOException {
int i = 0;
String s;
send(out, "LIST");
receive(in);
while((s = receive(in)) != null) {
if (!(s.equals("."))) {
i++;
}
else
return i;
}
return 0;
}
}
Done! Happy Coding!
Related posts:
Từ khóa this và super trong Java
Hướng dẫn Java Design Pattern – Mediator
Từ khóa throw và throws trong Java
Java String Conversions
Copy a List to Another List in Java
Introduction to the Functional Web Framework in Spring 5
Lập trình đa luồng trong Java (Java Multi-threading)
A Guide to Spring Boot Admin
Spring Boot - Rest Controller Unit Test
Introduction to Spring Cloud Netflix – Eureka
Reactive WebSockets with Spring 5
The Basics of Java Security
Chuyển đổi giữa các kiểu dữ liệu trong Java
String Initialization in Java
Lớp HashMap trong Java
Spring WebClient Filters
Biểu thức Lambda trong Java 8 – Lambda Expressions
Lớp lồng nhau trong java (Java inner class)
Chuyển đổi Array sang ArrayList và ngược lại
Mapping a Dynamic JSON Object with Jackson
Java Program to Implement Best-First Search
Java Program to Implement Solovay Strassen Primality Test Algorithm
Java Program to Implement Hash Tables with Double Hashing
Pagination and Sorting using Spring Data JPA
Most commonly used String methods in Java
Java Program to Perform Searching Based on Locality of Reference
Jackson Exceptions – Problems and Solutions
Java Program to Implement Trie
XML-Based Injection in Spring
Java Program to Implement Max Heap
Entity To DTO Conversion for a Spring REST API
Java InputStream to String