我想启动一个无论是否有客户端都会运行的服务器,但是当我按下连接按钮时,即使我为函数runServer()
启动了一个新线程,它也会挂起(GUI)。
在此先感谢,并表示感谢。
class HandleAClient implements Runnable {
private Socket socket;
public HandleAClient(Socket socket){
this.socket = socket;
}
@Override
public void run() {
try{
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
}catch(IOException ioex){
System.err.println(ioex);
}
}
}
//==========================================================================
//==========================================================================
private void runServer()
{
try{
while(true){
Socket socket = server.accept();
HandleAClient task = new HandleAClient(socket);
new Thread(task).start();
}
}catch(IOException ioex){
ioex.printStackTrace();
}
}//end method runServer
//=====================================================================
//=====================================================================
private void Connect_BtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
username = UserName_TF.getText();
passwordtext = Password_TF.getText();
try {
conn = DriverManager.getConnection(url, username, passwordtext);
if(conn.isValid(0))
connected = true;
jButton3.setEnabled(true);
jLabel4.setText("Connected");
UserName_TF.setEnabled(false);
Password_TF.setEnabled(false);
//java.awt.EventQueue.invokeLater(() -> {
runServer();
//});
} catch (SQLException e) {
//System.err.println(e);
JOptionPane.showMessageDialog(null, e);
}
}
答案 0 :(得分:0)
我将代码更改为以下内容(感谢Vince推荐)
public class MyThread extends Thread {
//private int var;
public MyThread() {
//this.var = var;
}
@Override
public void run() {
try {
while (true) {
Socket socket = server.accept();
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
}
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//=========================================================================
private void Connect_BtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
username = UserName_TF.getText();
passwordtext = Password_TF.getText();
try {
conn = DriverManager.getConnection(url, username, passwordtext);
if(conn.isValid(0))
connected = true;
jButton3.setEnabled(true);
jLabel4.setText("Connected");
UserName_TF.setEnabled(false);
Password_TF.setEnabled(false);
//JOptionPane.showMessageDialog(null, "Connection Established");
new Login.MyThread().start();
} catch (SQLException e) {
//System.err.println(e);
JOptionPane.showMessageDialog(null, e);
}
}