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:
Simple Single Sign-On with Spring Security OAuth2
HandlerAdapters in Spring MVC
Hướng dẫn Java Design Pattern – Chain of Responsibility
Lớp Arrarys trong Java (Arrays Utility Class)
The Java 8 Stream API Tutorial
Java Program to Perform Encoding of a Message Using Matrix Multiplication
ArrayList trong java
Java Program to Implement RenderingHints API
Spring Boot - Google OAuth2 Sign-In
Spring Data JPA @Query
Guide to Java OutputStream
Spring Data MongoDB Transactions
CharSequence vs. String in Java
Handle EML file with JavaMail
How to Kill a Java Thread
Java Program to Compute Determinant of a Matrix
Guide to the Java TransferQueue
Spring WebFlux Filters
Concurrent Test Execution in Spring 5
Java Program to Implement Binary Tree
REST Web service: Tạo ứng dụng Java RESTful Client với Jersey Client 2.x
Getting Started with GraphQL and Spring Boot
Spring REST with a Zuul Proxy
Java Program to Implement Aho-Corasick Algorithm for String Matching
Simple Single Sign-On with Spring Security OAuth2
Java Program to Check Whether a Directed Graph Contains a Eulerian Cycle
Java Program to Implement Multi-Threaded Version of Binary Search Tree
Assertions in JUnit 4 and JUnit 5
Java Program to Implement Tarjan Algorithm
Loại bỏ các phần tử trùng trong một ArrayList như thế nào?
Java Program to Implement the Hill Cypher
LinkedHashSet trong java