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:
Transactions with Spring and JPA
Java Program to Implement Pollard Rho Algorithm
Spring WebClient Requests with Parameters
Find the Registered Spring Security Filters
ETags for REST with Spring
Java Program to Use rand and srand Functions
@Lookup Annotation in Spring
Spring Boot with Multiple SQL Import Files
Spring Boot - Actuator
Java Program to Find MST (Minimum Spanning Tree) using Kruskal’s Algorithm
Java Program to Implement Sorted Circular Doubly Linked List
Most commonly used String methods in Java
Custom JUnit 4 Test Runners
Wiring in Spring: @Autowired, @Resource and @Inject
Examine the internal DNS cache
Mapping a Dynamic JSON Object with Jackson
Array to String Conversions
Partition a List in Java
Giới thiệu JDBC Connection Pool
An Intro to Spring Cloud Vault
Java Program to Implement Control Table
Spring Boot - Sending Email
XML Serialization and Deserialization with Jackson
Java Program to implement Sparse Vector
Java Program to Implement CopyOnWriteArrayList API
Thao tác với tập tin và thư mục trong Java
Java Program to Check whether Directed Graph is Connected using DFS
Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected
Giới thiệu HATEOAS
Dynamic Proxies in Java
Java Program to Implement Ford–Fulkerson Algorithm
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence