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:
Spring Security Registration – Resend Verification Email
Java Program to Generate a Sequence of N Characters for a Given Specific Case
Java – InputStream to Reader
Java Program to Implement Sieve Of Sundaram
Returning Custom Status Codes from Spring Controllers
CharSequence vs. String in Java
Java Program to Solve any Linear Equation in One Variable
Sử dụng JDBC API thực thi câu lệnh truy vấn dữ liệu
Giới thiệu Google Guice – Aspect Oriented Programming (AOP)
An Introduction to ThreadLocal in Java
Java Program to Implement Floyd-Warshall Algorithm
Guide to the Volatile Keyword in Java
Java Program to Implement Kosaraju Algorithm
Guide to DelayQueue
JUnit5 @RunWith
The Thread.join() Method in Java
Java Program to Implement Hash Tables Chaining with List Heads
Java Program to Implement an Algorithm to Find the Global min Cut in a Graph
An Introduction to Java.util.Hashtable Class
Custom HTTP Header with the HttpClient
A Guide to JUnit 5 Extensions
Transaction Propagation and Isolation in Spring @Transactional
Java Program to Implement Maximum Length Chain of Pairs
Java Program to Implement Interpolation Search Algorithm
Spring Boot - Unit Test Cases
Quick Guide to the Java StringTokenizer
Spring Webflux and CORS
Java Program to Check whether Undirected Graph is Connected using BFS
Java Program to Create a Balanced Binary Tree of the Incoming Data
Java Program to Implement Sorted Circularly Singly Linked List
Java String Conversions
Using a List of Values in a JdbcTemplate IN Clause