我正在开始一个基于GUI的项目,用于购物和下载电子书
到目前为止,我有四个类:Client,Server,ServerThread和Login(GUI表单)
当我输入用户名和密码并点击“登录”按钮时程序卡住了
我在命令行上运行Server,从NetBeans登录,它们似乎已连接
Socket.isConnected()返回true
此外,有一次我认为我不小心运行了两个登录,并且它有效并且没有卡在其中一个上。
任何想法为什么会这样?
Client.java
package Client;
import java.io.*;
import java.net.*;
public class Client {
private static final int PORT = 9000;
Socket sock;
BufferedReader input;
PrintWriter output;
public Client () {
try {
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
sock = new Socket (serverIP,PORT);
input = new BufferedReader ( new InputStreamReader (sock.getInputStream()));
output = new PrintWriter (new BufferedWriter (new OutputStreamWriter ( sock.getOutputStream())),true);
}
catch (Exception e) {
System.out.println(e);
}
}
public boolean login(String user, String password) {
output.write("LOGIN " + user + "#" + password); //information about user and password are in a form "user#password" in users.txt
output.flush();
String response = null;
try {
response = input.readLine();
}
catch (IOException e) {
System.out.println(e);
}
if (response != null) {
return response.equals("SUCCESS");
}
return false;
}
}
Server.java
package Server;
import java.io.*; import java.net.*;
public class Server {
private static final int PORT = 9000;
public static void main (String[] args) {
try {
ServerSocket serversocket = new ServerSocket(PORT);
while (true) {
Socket sock = serversocket.accept();
//new ServerThread(sock).start();
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
ServerThread.java
package Server;
import java.net.*;
import java.io.*;
public class ServerThread extends Thread {
private Socket sock;
private BufferedReader input;
private PrintWriter output;
public ServerThread (Socket sock) {
System.out.println("ServerThread konstruktor");
this.sock = null;
try {
this.sock = sock;
input = new BufferedReader ( new InputStreamReader (sock.getInputStream()));
output = new PrintWriter (new BufferedWriter (new OutputStreamWriter ( sock.getOutputStream())),true);
}
catch (Exception e) {
System.out.println(e);
}
}
@Override
public void run() {
System.out.println("ServerThread.run()");
while (true) {
try {
String request = null;
request = input.readLine();
if ( request.startsWith("LOGIN")) {
String userpass = request.split(" ")[1];
BufferedReader citac;
citac = new BufferedReader (new FileReader ("C:\\Users\\HP USER\\Documents\\NetBeansProjects\\Bookholic\\src\\resources\\users.txt"));
String line = null;
while ( (line = citac.readLine()) != null) {
if (line.equals(userpass)) {
output.write("SUCCESS");
output.flush();
break;
}
}
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
}
Login.java
package gui;
import Client.Client;
public class Login extends javax.swing.JFrame {
Client client;
public Login() {
initComponents();
client = new Client();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
btnLogin = new javax.swing.JButton();
tbUsername = new javax.swing.JTextField();
tbPassword = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnLogin.setText("Login");
btnLogin.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btnPrijavaMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(170, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnLogin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(tbUsername)
.addComponent(tbPassword))
.addGap(165, 165, 165))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(115, Short.MAX_VALUE)
.addComponent(tbUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addComponent(tbPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnLogin)
.addGap(78, 78, 78))
);
pack();
}// </editor-fold>
private void btnLoginMouseClicked(java.awt.event.MouseEvent evt) {
if (client.login(tbUsername.getText(),tbPassword.getText())) {
System.out.println("SUCCESS");
}
else {
System.out.println("FAIL");
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnLogin;
private javax.swing.JTextField tbUsername;
private javax.swing.JTextField tbPassword;
// End of variables declaration
}
可能存在编译错误,因为我在复制粘贴时更正了某些变量的名称 here 。 此外,ServerThread.run()实现为while-loop,因为用户将做很多事情,除了登录,我将在稍后添加。