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:
Set Interface trong Java
Template Engines for Spring
Java 8 StringJoiner
Spring Cloud Bus
Assertions in JUnit 4 and JUnit 5
Java Program to Implement a Binary Search Tree using Linked Lists
Hướng dẫn Java Design Pattern – Strategy
Spring Boot - File Handling
Tips for dealing with HTTP-related problems
Java Program to Represent Linear Equations in Matrix Form
Thao tác với tập tin và thư mục trong Java
Java Program to Perform Optimal Paranthesization Using Dynamic Programming
Partition a List in Java
String Processing with Apache Commons Lang 3
Get the workstation name or IP
Hướng dẫn Java Design Pattern – State
Java Program to Print the Kind of Rotation the AVL Tree is Undergoing
Java Program to Implement Segment Tree
A Guide to the Java LinkedList
Converting a List to String in Java
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x
JUnit5 Programmatic Extension Registration with @RegisterExtension
Ignore Null Fields with Jackson
Java Program to Implement Efficient O(log n) Fibonacci generator
How to Get the Last Element of a Stream in Java?
Spring Boot with Multiple SQL Import Files
Guide to the ConcurrentSkipListMap
Truyền giá trị và tham chiếu trong java
The Difference Between Collection.stream().forEach() and Collection.forEach()
Tổng quan về ngôn ngữ lập trình java
Ways to Iterate Over a List in Java
Registration with Spring Security – Password Encoding