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:
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Hướng dẫn Java Design Pattern – Command
Spring @RequestParam Annotation
Request Method Not Supported (405) in Spring
Java Program to Implement Red Black Tree
Java Program to Implement ArrayBlockingQueue API
Java Program to Compute Discrete Fourier Transform Using Naive Approach
Java Program to Implement Bresenham Line Algorithm
Object Type Casting in Java
ArrayList trong java
Auditing with JPA, Hibernate, and Spring Data JPA
Lớp Properties trong java
Java Program to Implement Disjoint Sets
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Hướng dẫn Java Design Pattern – Decorator
A Guide to System.exit()
The XOR Operator in Java
Spring Cloud – Tracing Services with Zipkin
Remove the First Element from a List
Java Program to Implement Best-First Search
Custom Thread Pools In Java 8 Parallel Streams
Java Program to Perform the Unique Factorization of a Given Number
Java Program to Compute DFT Coefficients Directly
Java Program to Check if an UnDirected Graph is a Tree or Not Using DFS
Java Program to Implement Hash Tables with Quadratic Probing
Guide to Java OutputStream
Serialization và Deserialization trong java
A Guide to Iterator in Java
Java – InputStream to Reader
Spring Security Form Login
Java Program to Implement Warshall Algorithm
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters