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 Guava Multimap
Automatic Property Expansion with Spring Boot
Spring Boot Integration Testing with Embedded MongoDB
Properties with Spring and Spring Boot
Giới thiệu HATEOAS
Join and Split Arrays and Collections in Java
Java Program to Implement Bloom Filter
Java Program to Implement the Program Used in grep/egrep/fgrep
Introduction to Spring Data JDBC
Java Program to Implement Efficient O(log n) Fibonacci generator
Java 8 Stream findFirst() vs. findAny()
Java Program to Implement SynchronosQueue API
Prevent Brute Force Authentication Attempts with Spring Security
Constructor Injection in Spring with Lombok
Spring Security – Reset Your Password
Java Program to Implement Insertion Sort
RegEx for matching Date Pattern in Java
Introduction to Spring Method Security
Guava – Join and Split Collections
Java Program to Generate Random Numbers Using Multiply with Carry Method
Mệnh đề Switch-case trong java
Using a Mutex Object in Java
Guide to @JsonFormat in Jackson
Java Program to implement Associate Array
Recommended Package Structure of a Spring Boot Project
Java Program to Implement Lloyd’s Algorithm
Guide To CompletableFuture
Tiêu chuẩn coding trong Java (Coding Standards)
Deploy a Spring Boot App to Azure
Java Program to Implement Max Heap
Java Program to Implement Gift Wrapping Algorithm in Two Dimensions
Using a Custom Spring MVC’s Handler Interceptor to Manage Sessions