java swing 端口连接 测试
时间: 2023-09-15 07:19:02 浏览: 77
swing代码,自己测试用
你可以使用以下代码来测试Java Swing端口连接:
```java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class PortConnectionTest extends JFrame implements ActionListener {
private JLabel statusLabel;
private JTextField hostField;
private JTextField portField;
public PortConnectionTest() {
super("Port Connection Test");
JPanel inputPanel = new JPanel();
inputPanel.add(new JLabel("Host:"));
hostField = new JTextField(20);
inputPanel.add(hostField);
inputPanel.add(new JLabel("Port:"));
portField = new JTextField(5);
inputPanel.add(portField);
JButton connectButton = new JButton("Connect");
connectButton.addActionListener(this);
inputPanel.add(connectButton);
statusLabel = new JLabel(" ");
JPanel statusPanel = new JPanel();
statusPanel.add(statusLabel);
add(inputPanel, BorderLayout.NORTH);
add(statusPanel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 100);
setVisible(true);
}
public static void main(String[] args) {
new PortConnectionTest();
}
@Override
public void actionPerformed(ActionEvent e) {
String host = hostField.getText();
int port = Integer.parseInt(portField.getText());
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(host, port), 1000);
statusLabel.setText("Connected successfully!");
socket.close();
} catch (IOException ex) {
statusLabel.setText("Connection failed!");
}
}
}
```
这个程序创建了一个简单的Swing界面,允许用户输入主机和端口号。当用户点击“连接”按钮时,程序将尝试连接到指定的主机和端口。如果连接成功,标签将显示“连接成功!”;否则,标签将显示“连接失败!”。
你可以使用这个程序来测试你的Java应用程序是否能够成功连接到指定的主机和端口。
阅读全文