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:
An Intro to Spring Cloud Security
Java Program to Find MST (Minimum Spanning Tree) using Prim’s Algorithm
Hướng dẫn Java Design Pattern – Prototype
Spring Boot - Hystrix
Using Custom Banners in Spring Boot
HttpClient Basic Authentication
Java Program to Implement Trie
Java Program to Implement Sparse Matrix
Handling URL Encoded Form Data in Spring REST
Java toString() Method
Spring Cloud AWS – EC2
Java Program to Find MST (Minimum Spanning Tree) using Kruskal’s Algorithm
How to Change the Default Port in Spring Boot
Validate email address exists or not by Java Code
Jackson Annotation Examples
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Spring Boot - Tomcat Deployment
Serialize Only Fields that meet a Custom Criteria with Jackson
Guide to CountDownLatch in Java
Java 8 StringJoiner
Java Program to Perform Right Rotation on a Binary Search Tree
Java InputStream to Byte Array and ByteBuffer
A Quick Guide to Using Keycloak with Spring Boot
A Guide to JUnit 5 Extensions
The HttpMediaTypeNotAcceptableException in Spring MVC
Using the Not Operator in If Conditions in Java
Chương trình Java đầu tiên
Java Program to Implement Dijkstra’s Algorithm using Queue
Java – Byte Array to Reader
Java Program to Describe the Representation of Graph using Incidence Matrix
Java Program to Implement Radix Sort
Tạo ứng dụng Java RESTful Client với thư viện Retrofit