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:
Java Program to Implement LinkedTransferQueue API
How To Serialize and Deserialize Enums with Jackson
Spring WebClient Filters
Spring Boot - Zuul Proxy Server and Routing
Guide to the Java Queue Interface
Java Collections Interview Questions
Prevent Cross-Site Scripting (XSS) in a Spring Application
Java NIO2 Path API
Spring Security with Maven
Getting Started with Forms in Spring MVC
Extract links from an HTML page
Tạo ứng dụng Java RESTful Client với thư viện OkHttp
Làm thế nào tạo instance của một class mà không gọi từ khóa new?
Java Program to Optimize Wire Length in Electrical Circuit
Convert a Map to an Array, List or Set in Java
Spring Boot: Customize Whitelabel Error Page
Java Program to Implement Binomial Tree
An Introduction to ThreadLocal in Java
How to Read HTTP Headers in Spring REST Controllers
Java Program to Implement HashMap API
Java Convenience Factory Methods for Collections
Spring MVC Content Negotiation
Hamcrest Collections Cookbook
Send an email using the SMTP protocol
Server-Sent Events in Spring
Collect a Java Stream to an Immutable Collection
Spring Boot with Multiple SQL Import Files
Apache Commons Collections OrderedMap
Spring Boot Tutorial – Bootstrap a Simple Application
REST Web service: Upload và Download file với Jersey 2.x
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Adding a Newline Character to a String in Java