coolsunxu
coolsunxu
2016-09-27 15:55
采纳率: 66.7%
浏览 1.2k
已采纳

怎么解决java网络通信编程ip和port是从文本框中获取的?

为什么我把connect()方法加入button1的事件中就会黑屏

代码如下
客户端:
package sunxu.util;

import java.awt.BorderLayout;
import java.awt.Dimension;
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.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.BorderFactory;
import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ClientSocketFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private PrintWriter writer; // 声明PrintWriter类对象
private BufferedReader reader; // 声明BufferedReader对象
private Socket socket; // 声明Socket对象
private JTextArea ta_info; // 创建JtextArea对象
JButton button1 = new JButton("Connect");
//private JTextField tf_send; // 创建JtextField对象
private InetAddress sendIp;
private int sendPort;

private void connect() { // 连接套接字方法
    ta_info.append("Connect to server…\n"); // 文本域中信息信息
    try { // 捕捉异常
        socket = new Socket(sendIp,sendPort); // 实例化Socket对象
        while (true) {
            writer = new PrintWriter(socket.getOutputStream(), true);
            reader = new BufferedReader(new InputStreamReader(socket
                    .getInputStream())); // 实例化BufferedReader对象
            ta_info.append("Client connected…\n"); // 文本域中提示信息
            getServerInfo();
        }
    } catch (Exception e) {
        e.printStackTrace(); // 输出异常信息
    }
}

public static void main(String[] args) { // 主方法
      ClientSocketFrame clien = new ClientSocketFrame(); // 创建本例对象
      clien.setVisible(true); // 将窗体显示
      //clien.connect(); // 调用连接方法
}

private void getServerInfo() {
    try {
        while (true) {
            if (reader != null) {
                String line = reader.readLine();// 读取服务器发送的信息
                if (line != null)
                    ta_info.append("接收到服务器发送的信息:" + line + "\n"); // 显示服务器端发送的信息
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (reader != null) {
                reader.close();// 关闭流
            }
            if (socket != null) {
                socket.close(); // 关闭套接字
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * Create the frame
 */
public ClientSocketFrame() {
    super();
    setTitle("客户端");
    setBounds(100, 100, 361, 257);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final JPanel panel = new JPanel();
    getContentPane().add(panel, BorderLayout.NORTH);

    panel.setBorder(BorderFactory.createTitledBorder("客户机设置:"));



    final JLabel label = new JLabel();
    label.setText("Server IP:");
    panel.add(label);
    JTextField tf_sen= new JTextField();
    tf_sen.setPreferredSize(new Dimension(50, 25));
    panel.add(tf_sen);

    final JLabel label1 = new JLabel();
    label1.setText("Server Port:");
    panel.add(label1);
    JTextField tf_Port = new JTextField();
    tf_Port.setPreferredSize(new Dimension(50, 25));
    panel.add(tf_Port);

    final JButton button1 = new JButton("Connect");

    button1.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent e) {
            try {
                sendIp=InetAddress.getByName(tf_sen.getText());
            } catch (UnknownHostException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }  
               sendPort=Integer.parseInt(tf_Port.getText());
               ta_info.append("Connect to server…\n"); // 文本域中信息信息
               ta_info.append(sendIp+"\n"); // 文本域中信息信息
               ta_info.append(sendPort+"\n"); // 文本域中信息信息
               connect();
        }
    });
    panel.add(button1);


    final JPanel panel_1 = new JPanel();
    getContentPane().add(panel_1, BorderLayout.SOUTH);

    final JLabel label_1 = new JLabel();
    label_1.setText("Say:");
    panel_1.add(label_1);

    JTextField tf_send = new JTextField();
    tf_send.setPreferredSize(new Dimension(220, 25));
    panel_1.add(tf_send);

    final JButton button = new JButton();
    button.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent e) {
            writer.println(tf_send.getText()); // 将文本框中信息写入流
            ta_info.append("客户端发送的信息:" + tf_send.getText()
                    + "\n"); // 将文本框中信息显示在文本域中
            tf_send.setText(""); // 将文本框清空
        }
    });
    button.setText("Say");
    panel_1.add(button);

    final JScrollPane scrollPane = new JScrollPane();
    getContentPane().add(scrollPane, BorderLayout.CENTER);

    ta_info = new JTextArea();
    scrollPane.setViewportView(ta_info);
    //

}

}

服务器:
package sunxu.util;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ServerSocketFrame extends JFrame {
//private JTextField tf_send;
private JTextArea ta_info;
private PrintWriter writer; // 声明PrintWriter类对象
private BufferedReader reader; // 声明BufferedReader对象
private ServerSocket server; // 声明ServerSocket对象
private Socket socket; // 声明Socket对象socket
private int sendPort;

public void getServer() {
    try {
        server = new ServerSocket(sendPort); // 实例化Socket对象
        ta_info.append("服务器套接字已经创建成功\n"); // 输出信息
        while (true) { // 如果套接字是连接状态
            ta_info.append("等待客户机的连接......\n"); // 输出信息
            socket = server.accept(); // 实例化Socket对象
            reader = new BufferedReader(new InputStreamReader(socket
                    .getInputStream())); // 实例化BufferedReader对象
            writer = new PrintWriter(socket.getOutputStream(), true);
            getClientInfo(); // 调用getClientInfo()方法
        }
    } catch (Exception e) {
        e.printStackTrace(); // 输出异常信息
    }
}

private void getClientInfo() {
    try {
        while (true) {
            String line = reader.readLine();// 读取客户端发送的信息
            if (line != null)
                ta_info.append("接收到客户机发送的信息:" + line + "\n"); // 显示客户端发送的信息
        }
    } catch (Exception e) {
        ta_info.append("客户端已退出。\n"); // 输出异常信息
    } finally {
        try {
            if (reader != null) {
                reader.close();// 关闭流
            }
            if (socket != null) {
                socket.close(); // 关闭套接字
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static void main(String[] args) { // 主方法
    ServerSocketFrame frame = new ServerSocketFrame(); // 创建本类对象
    frame.setVisible(true);
    //frame.getServer(); // 调用方法
}

public ServerSocketFrame() {
    super();
    setTitle("服务器端程序");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 379, 260);

    final JScrollPane scrollPane = new JScrollPane();
    getContentPane().add(scrollPane, BorderLayout.CENTER);

    ta_info = new JTextArea();
    scrollPane.setViewportView(ta_info);

    final JPanel panel = new JPanel();
    getContentPane().add(panel, BorderLayout.SOUTH);

    final JLabel label = new JLabel();
    label.setText("Say:");
    panel.add(label);

    JTextField tf_send = new JTextField();
    tf_send.setPreferredSize(new Dimension(150, 25));
    panel.add(tf_send);

    final JButton button = new JButton();
    button.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent e) {
            writer.println(tf_send.getText()); // 将文本框中信息写入流
            ta_info.append("服务器发送的信息是:" + tf_send.getText() + "\n"); // 将文本框中信息显示在文本域中
            tf_send.setText(""); // 将文本框清空
        }
    });
    button.setText("Say:");
    panel.add(button);

    final JPanel panel_1 = new JPanel();
    getContentPane().add(panel_1, BorderLayout.NORTH);
    panel_1.setBorder(BorderFactory.createTitledBorder("服务器设置:"));

    final JLabel label_1 = new JLabel();
    label_1.setText("Port:");
    JTextField tf_sen= new JTextField();
    tf_sen.setPreferredSize(new Dimension(220, 25));
    panel_1.add(label_1);
    panel_1.add(tf_sen);

    final JButton button1 = new JButton("Strat");

    button1.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent e) {
               sendPort=Integer.parseInt(tf_sen.getText());
               getServer();
        }
    });
    panel_1.add(button1);


}

}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • coolsunxu
    coolsunxu 2017-03-28 15:02
    已采纳

    这种问题是要考虑线程的

    点赞 评论
  • devmiao
    devmiao 2016-09-27 15:57
    点赞 评论
  • zqbnqsdsmd
    zqbnqsdsmd 2016-09-27 16:14

    阻塞的方法,需要看下线程

    点赞 评论

相关推荐