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:
Guide to DelayQueue
Java Program to Implement Queue
Đồng bộ hóa các luồng trong Java
Spring AMQP in Reactive Applications
Lập trình đa luồng trong Java (Java Multi-threading)
A Guide to TreeMap in Java
Java Program to Implement Aho-Corasick Algorithm for String Matching
Spring Boot - Admin Client
Using JWT with Spring Security OAuth (legacy stack)
Từ khóa throw và throws trong Java
Tránh lỗi NullPointerException trong Java như thế nào?
Java Program to Perform Addition Operation Using Bitwise Operators
Generic Constructors in Java
Java IO vs NIO
Mệnh đề Switch-case trong java
Create a Custom Auto-Configuration with Spring Boot
HandlerAdapters in Spring MVC
Hướng dẫn Java Design Pattern – Strategy
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Spring MVC Tutorial
Java Program to Perform Matrix Multiplication
Stack Memory and Heap Space in Java
Introduction to the Java NIO2 File API
Java Program to Implement Max Heap
Hướng dẫn Java Design Pattern – Flyweight
Java Program to Implement Binomial Heap
Java 14 Record Keyword
Introduction to Spring Boot CLI
Luồng Daemon (Daemon Thread) trong Java
Java Program to Implement Fenwick Tree