使用套接字和线程编写文件

时间:2015-05-22 14:51:17

标签: java multithreading sockets

我有一个客户端/服务器应用程序使用套接字,客户端逐行输入文本。在服务器端,我希望一个线程一次接收一行文本,第二个线程应该将同一行写入文件。这一直持续到客户停止。我的服务器正在接收文本行,但第二个线程没有将其写入文件。

以下是接收文本的服务器线程代码。

StructLayout

以下是写入文件

的线程
public class EchoServer extends Thread {
    public static String line = "none";

    public EchoServer(int portnum) {
        try {
            server = new ServerSocket(portnum);
        } catch (Exception err) {
            System.out.println(err);
        }
    }

    public void run() {
        try {
            while (true) {
                Socket client = server.accept();
                BufferedReader r = new BufferedReader(
                        new InputStreamReader(client.getInputStream()));
                PrintWriter w = new PrintWriter(client.getOutputStream(),
                        true);
                // w.println("Welcome to the Java EchoServer.  Type 'bye' to close.");
                while ((line = r.readLine()) != null) {
                    // read from Cleint
                    if (line != null) {
                        // p.destroy();
                        System.out.println(line);
                        // sleep(2000);
                    }
                    Thread.yield();
                }
                client.close();
            }
        } catch (Exception err) {
            System.err.println(err);
        }
    }
    private ServerSocket server;
}

以下是主要功能

public class paste extends Thread {
    // To create producer and consumer as threads
    // Shared variable
    public static int x = 0; // Maximum Limit to simulate a buffer
    public String l;
    public static int j = 1;

    public void run() {
        System.out.println("n");
        if (EchoServer.line != "none") {
            String fileName = "c:/sys prg lab/salfar1.txt";
            try {
                // Assume default encoding.
                FileWriter fileWriter = new FileWriter(fileName, true);
                // Always wrap FileWriter in BufferedWriter.
                BufferedWriter bufferedWriter = new BufferedWriter(
                        fileWriter);
                // Note that write() does not automatically
                // append a newline character.
                bufferedWriter.write(EchoServer.line);
                bufferedWriter.newLine();
                System.out.println("y");
                EchoServer.line = "none";
                // Always close files.
                bufferedWriter.close();
            } catch (IOException ex) {
                System.out.println("Error writing to file '" + fileName
                        + "'");
                // Or we could just do this:
                // ex.printStackTrace();
            }
            Thread.yield();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

在我看来,你的第二个线程运行一次然后退出,所以当你的服务器收到文本时,编写器线程已经返回。 尝试使用while(true),就像在服务器线程中一样。