我是剛上大學的新手,JAVA課設做聊天室,可是我的檔案總是傳不過去

川酒厄發表於2020-12-26

我是剛上大學的新手,課設做聊天室,可是我的檔案總是傳不過去

我不懂那個監聽器的介面怎麼用,就像我程式碼裡面那個

jbt.addActionListener(this);

我搞不明白this到底指的什麼,文字還可以傳,但是要傳檔案的時候就不可以,我就問了問同學他們直接寫的監聽器,我知道這個程式碼漏洞百出。求求各位幫我指點一下錯誤在哪,謝謝各位了。
下面是客戶端的程式碼:

package yigeshishi;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ClientChatMain extends JFrame implements ActionListener{
    public static void main(String[] args){
        new ClientChatMain();
    }

    //bw更改區域性變數定義
    static BufferedWriter bw = null;
    static private JTextArea jta;
    static private JTextField jtf;
    SimpleDateFormat sdf=new SimpleDateFormat("MM-dd HH:mm:ss");
    Date date=new Date();
    String now=sdf.format(date);

    public ClientChatMain(){
        //文字域
        jta = new JTextArea();
        jta.setEditable(false);//不可編輯
        //滾動條
        JScrollPane jsp = new JScrollPane(jta);
        //輸入皮膚
        JPanel jp = new JPanel();
        //輸入文字框
        jtf = new JTextField(17);
        //傳送按鈕
        JButton jbt = new JButton("傳送");
        JButton jb = new JButton("檔案傳送");
        jp.add(jtf);
        jp.add(jbt);
        jp.add(jb);
        //加入窗體中
        this.add(jsp, BorderLayout.CENTER);
        this.add(jp,BorderLayout.SOUTH);

        this.setTitle("客戶端");
        this.setSize(400,400);
        this.setLocation(900,400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);

        //客戶端
        try{
            jbt.addActionListener(this);
            //建立文字通訊客戶端Socket
            Socket cs = new Socket(("127.0.0.1"),0113);
            //輸入流
            InputStream in = cs.getInputStream();//因為客戶端自動搜尋連線所以這裡和服務端不同,這裡getInputStream()方法歸屬於上面命名的cs
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            //輸出流
            OutputStream out = cs.getOutputStream();
            bw = new BufferedWriter(new OutputStreamWriter(out));
            //迴圈讀取資料
            String Line;
            while((Line = br.readLine())!=null){
                jta.append(now + "\n" + Line+System.lineSeparator());
            }
            //關閉
            cs.close();
        }catch(IOException e){
            e.printStackTrace();
        }
        try {
            //建立檔案傳輸Socket
            Socket cs1 = new Socket("127.0.0.1", 1012);
            //檔案傳輸監聽器
            jb.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    new Thread(){
                        public void run(){
                            try{
                                File file = new File("D:\\upload\\hello.jpg");

                                if(!file.exists()){
                                    file.createNewFile();
                                }else{
                                    file.delete();
                                    file.createNewFile();
                                }

                                RandomAccessFile raf = new RandomAccessFile(file,"rw");
                                InputStream is =cs1.getInputStream();
                                InputStream in = new DataInputStream(new BufferedInputStream(is));

                                byte[] buf = new byte[3072];
                                int num = in.read(buf);
                                while(num != -1){
                                    raf.write(buf,0,num);
                                    raf.skipBytes(num);
                                    num = in.read(buf);
                                }
                                //關閉
                                raf.close();
                            }catch (IOException e1){
                                e1.printStackTrace();
                            }
                        }
                    }.start();
                }
            });
        }catch(IOException e3){
            e3.printStackTrace();
        }
    }
    //傳送按鈕繫結監聽點選事件
    @Override
    public void actionPerformed(ActionEvent e){
        //傳送內容
        String text = jtf.getText();
        text = "客戶端:" + text;
        jta.append( now + "\n" + text + System.lineSeparator());
        //傳送
        try{
            bw.write(text);
            bw.newLine();
            bw.flush();
        }catch(IOException e1){
            e1.printStackTrace();
        }
        jtf.setText("");
    }
}

然後是服務端的程式碼:

package yigeshishi;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ServerChatMain extends JFrame implements ActionListener{
    public static void main(String[] args) { new ServerChatMain(); }

    //關於監聽器的重寫用到這三個變數,可是如果一開始在服務端的模組裡定義的的話就只能是區域性變數,需要在外面定義賦值。
    static BufferedWriter bw = null;
    static private JTextArea jta;
    static private JTextField jtf;
    SimpleDateFormat sdf=new SimpleDateFormat("MM-dd HH:mm:ss");
    Date date=new Date();
    String now=sdf.format(date);

    public ServerChatMain(){
        //介面搭建
        //文字域
        jta = new JTextArea();
        jta.setEditable(false);//不可編輯
        //滾動條
        JScrollPane jsp = new JScrollPane(jta);
        //輸入皮膚
        JPanel jp = new JPanel();
        //輸入文字框
        jtf = new JTextField(17);
        //傳送按鈕
        JButton jbt = new JButton("傳送");
        JButton jb = new JButton("檔案傳送");
        jp.add(jtf);
        jp.add(jbt);
        jp.add(jb);
        //加入窗體中
        this.add(jsp, BorderLayout.CENTER);
        this.add(jp,BorderLayout.SOUTH);

        this.setTitle("服務端");
        this.setSize(400,400);
        this.setLocation(400,400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        //服務端(多執行緒版本)
        try {
            jbt.addActionListener(this);
            //建立服務端Socket
            ServerSocket ss = new ServerSocket(0113);
            while(true) {
                //等待客戶端連線
                Socket socket = ss.accept();
                //多執行緒
                new Thread(new Runnable(){
                    @Override
                    public void run(){
                        try{
                            //獲取Socket通道輸入流
                            InputStream in = socket.getInputStream();
                            BufferedReader br = new BufferedReader(new InputStreamReader(in));
                            //獲取Socket通道輸出流
                            OutputStream out = socket.getOutputStream();
                            bw = new BufferedWriter(new OutputStreamWriter(out));
                            //迴圈讀取資料
                            String Line;
                            while ((Line = br.readLine()) != null) {
                                jta.append( now + "\n " + Line + System.lineSeparator());
                            }
                            //關閉Socket通道
                            ss.close();
                        }catch(IOException e2){
                            e2.printStackTrace();
                        }
                    }
                }).start();
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        try{
            ServerSocket ss1 = new ServerSocket(1012);
            Socket cs1 =ss1.accept();
            jb.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    new Thread(){
                        public void run(){
                            try {
                                File file = new File("D:\\zhileng.jpg");
                                FileInputStream fis = new FileInputStream(file);

                                OutputStream os =cs1.getOutputStream();
                                OutputStream dos = new DataOutputStream(new BufferedOutputStream(os));

                                byte[] buf = new byte[3072];
                                int num = fis.read(buf);
                                while(num != -1){
                                    dos.write(buf,0,num);
                                    dos.flush();
                                    num=fis.read(buf);
                                }

                                jta.append(file + "傳送成功\n");
                                fis.close();
                            }catch(IOException e1){
                                e1.printStackTrace();
                            }
                        }
                    }.start();
                }
            });
        }catch(IOException e){
            e.printStackTrace();
        }
    }


    //傳送按鈕繫結監聽點選事件
    @Override
    public void actionPerformed(ActionEvent e) {
        //文字框傳送的內容
        String text = jtf.getText();
        text = "服務端:" + text;
        jta.append( now + "\n" + text + System.lineSeparator());
        //傳送
        try {
            bw.write(text);
            bw.newLine();
            bw.flush();
        }catch(IOException e1){
            e1.printStackTrace();
        }
        //清空文字框的內容
        jtf.setText("");
    }
}

實在侍弄不懂到底為什麼了,謝謝各位。這個程式碼是我第一次寫漏洞肯定百出,在各位閒暇時間希望能幫幫小弟。

相關文章