51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

Java学习之路-NET-socket简单数据传输2

完成服务器端和客户端的双向通讯。
NET/SocketTest1.java


package cn.antraces.NET;

import javax.swing.; import java.awt.; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date;

public class SocketTest1 implements Runnable{

public JFrame jf;
public JPanel jp;
public JButton jButton_Send, jButton_Stop;
public JTextArea jTextArea;
public JTextField jTextField;
public JScrollPane jScrollPane;
public Socket socket1, socket2;
public ServerSocket serverSocket;
public BufferedReader bufferedReader;
public int m;
public boolean on;

@Override
public void run() {
    try {
        if (m == 1) {
            server();
            bufferedReader = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
            on = true;
            while (on){
                client();
            }
        } else if (m == 2) {
            on = true;
            socket2 = new Socket("127.0.0.1",23333);
            bufferedReader = new BufferedReader(new InputStreamReader(socket2.getInputStream()));
            while (on){
                client();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public SocketTest1(int m){
    this.m = m;
    String title = "";
    if (m == 1) {
        title = "服务端";
    } else if (m == 2) {
        title = "客户端";
    }

    JFrame jf = new JFrame(title);
    jf.setSize(400, 400);
    jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    jf.setLocationRelativeTo(null);
    jf.setResizable(false);

    JPanel jp = new JPanel(new FlowLayout());

    jTextField = new JTextField(16);
    jTextField.setFont(new Font(null, Font.PLAIN, 18));

    jButton_Send = new JButton("发送");
    jButton_Stop = new JButton("断开");

    jButton_Send.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {

            PrintWriter printWriter = null;
            try {
                if (m == 1)
                    printWriter = new PrintWriter(socket1.getOutputStream(), true);
                else if (m == 2)
                    printWriter = new PrintWriter(socket2.getOutputStream(), true);
            } catch (IOException e) {
                e.printStackTrace();
            }
            printWriter.println(jTextField.getText());
            String str = "";
            Date nowDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SSS");

            if ((str = jTextArea.getText()) != null) {
                jTextArea.append("\r\n" + sdf.format(nowDate.getTime()) + "\r\n  " + jTextField.getText());
            }

            jTextField.setText("");
        }
    });

    jButton_Stop.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            on = false;
            jTextField.setEditable(false);
            jTextArea.append("\r\n" + "-=-=-=-=-=-=-=-=-=-连接已断开-=-=-=-=-=-=-=-=-=-");
            try {
                if (socket1 != null)
                    socket1.close();
                if (socket2 != null)
                    socket2.close();
                if (serverSocket != null)
                    serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    jTextArea = new JTextArea(19, 32);
    jTextArea.setText("-=-=-=-=-=-=-=-=-=-连接已启动-=-=-=-=-=-=-=-=-=-");
    jTextArea.setLineWrap(false);
    jTextArea.setEnabled(false);
    jScrollPane = new JScrollPane(jTextArea);

    jp.add(jScrollPane);
    jp.add(jTextField);
    jp.add(jButton_Send);
    jp.add(jButton_Stop);

    jf.setContentPane(jp);
    jf.setVisible(true);

    Thread th = new Thread(this);
    th.start();
}

public void server() throws IOException {
    serverSocket = new ServerSocket(23333);
    socket1 = serverSocket.accept();
}

public void client() throws IOException {
    String str = bufferedReader.readLine();
    if (str != null) {
        Date nowDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SSS");
        if (m == 1)
            jTextArea.append("\r\nClient - " + sdf.format(nowDate.getTime()) + "\r\n  " + str);
        if (m == 2)
            jTextArea.append("\r\nServer - " + sdf.format(nowDate.getTime()) + "\r\n  " + str);
    }
}

public static void main (String[] args){
    new SocketTest1(1);
    new SocketTest1(2);
}

}


在上次代码的基础上改了一点点东西...

赞(2)
未经允许不得转载:工具盒子 » Java学习之路-NET-socket简单数据传输2