首页 > 解决方案 > 如何改进我的服务器和客户端“SMTP”代码?

问题描述

我被分配了一个尝试来实现一个提供有限功能的 SMTP 客户端-服务器协议,解决方案是执行一个与此转录类似的典型执行:

S: 220 [ip]
C: HELLO [email]
S: 250 Hello [email], pleased to meet you
C: MAIL FROM: <email1@email.com>
S: 250 ok
C: RCPT TO: <email2@email2.com>
S: 250 ok
C: DATA
S: 354 End data with <CR><LF>.<CR><LF>
C: Hello,
C: Test Email
C: .
S: 250 ok Message accepted for delivery
C: QUIT
S: 221 [ip] closing connection

本质上,它不应该发送任何电子邮件或任何东西,而是更多地模拟通过 SMTP 发送电子邮件的过程。

我采用了使用 Cases 和 Switches 的简单方法,因此当它读取数据时,它会准确打印出我想要的内容,但我想知道是否有办法获取客户端的输入并在服务器中读取它以生成类似于我写的成绩单的输出。还有我怎样才能更好地编码呢?

这是服务器代码:

 package TCPSocket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer{
    private ServerSocket server;

    /**
     * The TCPServer constructor initiate the socket
     * @param ipAddress
     * @param port
     * @throws Exception
     */
    public TCPServer(String ipAddress, int port) throws Exception {
        if (ipAddress != null && !ipAddress.isEmpty())
            this.server = new ServerSocket(port, 1, InetAddress.getByName(ipAddress));
        else
            this.server = new ServerSocket(0, 1, InetAddress.getLocalHost());
    }

    /**
     * The listen method listen to incoming client's datagrams and requests
     * @throws Exception
     */



    private void listen() throws Exception {
        // listen to incoming client's requests via the ServerSocket
        //add your code here
        String data = null;
        Socket client = this.server.accept();
        String clientAddress = client.getInetAddress().getHostAddress();
        System.out.println("\r\nNew client connection from " + clientAddress);

        // print received datagrams from client
        //add your code here
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        while ( (data = in.readLine()) != null ) {
            //System.out.println("\r\nMessage from " + clientAddress + ": " + data);

            switch (data){
                case("HELLO 192.168.56.1"):
                    System.out.println("\r\n250 Hello " + clientAddress + ", pleased to meet you");
                    break;
                case("MAIL FROM: <test1@gmail.com>"):
                    System.out.println("\r\n250 ok");
                    break;
                case("RCPT TO: <test@email.com>"):
                    System.out.println("\r\n250 ok");
                    break;
                case("DATA"):
                    System.out.println("\r\n354 End data with <CR><LF>.<CR><LF>");
                    break;
                case("."):
                    System.out.println("\r\nok Message accepted for delivery");
                    break;
                case("QUIT"):
                    System.out.println("\r\n221 " + clientAddress + " closing connection");
                    in.close();
                    break;
            }

            client.sendUrgentData(1);
        }
    }

    public InetAddress getSocketAddress() {
        return this.server.getInetAddress();
    }

    public int getPort() {
        return this.server.getLocalPort();
    }


    public static void main(String[] args) throws Exception {
        // set the server address (IP) and port number
        //add your code here
        String serverIP = "192.168.56.1"; // local IP address
        int port = 7077;

        if (args.length > 0) {
            serverIP = args[0];
            port = Integer.parseInt(args[1]);
        }
        // call the constructor and pass the IP and port
        //add your code here
        TCPServer server = new TCPServer(serverIP, port);
        System.out.println("\r\nRunning Server: " +
                "Host=" + server.getSocketAddress().getHostAddress() +
                " Port=" + server.getPort());
        System.out.println("220 " + serverIP);
        server.listen();
    }

}

这是客户端代码:

package TCPSocket;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class TCPClient{
    private Socket tcpSocket;
    private InetAddress serverAddress;
    private int serverPort;
    private Scanner scanner;


    /**
     * @param serverAddress
     * @param serverPort
     * @throws Exception
     */
    private TCPClient(InetAddress serverAddress, int serverPort) throws Exception {
        this.serverAddress = serverAddress;
        this.serverPort = serverPort;

        //Initiate the connection with the server using Socket.
        //For this, creates a stream socket and connects it to the specified port number at the specified IP address.
        //add your code here
        this.tcpSocket = new Socket(this.serverAddress, this.serverPort);
        this.scanner = new Scanner(System.in);
    }

    /**
     * The start method connect to the server and datagrams
     * @throws IOException
     */
    private void start() throws IOException {
        String input;

        //create a new PrintWriter from an existing OutputStream (i.e., tcpSocket).
        //This convenience constructor creates the necessary intermediateOutputStreamWriter, which will convert characters into bytes using the default character encoding
        //You may add your code in a loop so that client can keep send datagrams to server
        //add your code here

        while (true) {
            input = scanner.nextLine();
            PrintWriter output = new PrintWriter(this.tcpSocket.getOutputStream(), true);
            //output.println("hello " + serverAddress);
            output.println(input);
            output.flush();
        }
    }

    public static void main(String[] args) throws Exception {
        // set the server address (IP) and port number
        //add your code here
        InetAddress serverIP = InetAddress.getByName("192.168.56.1"); // local IP address
        int port = 7077;

        if (args.length > 0) {
            serverIP = InetAddress.getByName(args[0]);
            port = Integer.parseInt(args[1]);
        }

        // call the constructor and pass the IP and port
        //add your code here
        TCPClient client = new TCPClient(serverIP, port);
        System.out.println("\r\n Connected to Server: " + client.tcpSocket.getInetAddress());
        client.start();
    }
}

希望我所写的内容有意义,我感谢提供的任何反馈和帮助

标签: javaemailsmtp

解决方案


推荐阅读