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:
REST Web service: Basic Authentication trong Jersey 2.x
Spring Boot - Web Socket
An Intro to Spring Cloud Contract
Java Program to Find Minimum Element in an Array using Linear Search
Java Program to Implement Gaussian Elimination Algorithm
How to Add a Single Element to a Stream
Template Engines for Spring
Spring Boot - Exception Handling
Java Program to Compute Cross Product of Two Vectors
Injecting Prototype Beans into a Singleton Instance in Spring
Spring REST with a Zuul Proxy
Java Program to Perform Insertion in a 2 Dimension K-D Tree
Beans and Dependency Injection
Apache Commons Collections OrderedMap
Recommended Package Structure of a Spring Boot Project
Một số ký tự đặc biệt trong Java
Registration – Password Strength and Rules
Java Program to Perform Insertion in a BST
Java Program to Implement Repeated Squaring Algorithm
Adding a Newline Character to a String in Java
HashSet trong java
Compact Strings in Java 9
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Java Program to Implement Knight’s Tour Problem
Introduction to Spring Boot CLI
Hướng dẫn Java Design Pattern – MVC
XML Serialization and Deserialization with Jackson
Feign – Tạo ứng dụng Java RESTful Client
Java Program to Find All Pairs Shortest Path
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Java Program to Implement Max Heap
Java Program to Implement Binary Heap