我正在尝试使用java制作一个带有gui的多线程客户机/服务器聊天室。目前,我能够创建一个功能正常的注册页面和登录页面,使用我使用哈希Map实现的Map。当我登录时,它不会像我期望的那样启动服务器或客户机,而且我还从服务器收到一条消息,说明连接失败,但是我无法确定原因。
客户
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import static java.rmi.server.LogStream.log;
import java.util.Scanner;
public class chatClient extends javax.swing.JFrame {
Scanner scan ;
Socket socket = null;
DataInputStream input = null;
DataOutputStream output = null;
InetAddress ip;
public chatClient() { //constructor
try{
ip = InetAddress.getByName("localhost");
socket = new Socket(ip, Constants.PORT);
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
scan = new Scanner(System.in);
}catch(UnknownHostException ex){
log("Client : " + ex.getMessage());
}catch(IOException ex){
log("Client : " + ex.getMessage());
}
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
status = new javax.swing.JLabel();
connectToServer = new javax.swing.JButton();
privateConnection = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
messageArea = new javax.swing.JTextArea();
inputMessage = new java.awt.TextField();
sendMessage = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
status.setText("Logged in as:");
connectToServer.setText("Connect to server");
connectToServer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
connectToServerActionPerformed(evt);
}
});
privateConnection.setText("Private connection");
messageArea.setColumns(20);
messageArea.setRows(5);
jScrollPane1.setViewportView(messageArea);
inputMessage.setText("");
sendMessage.setText("Send");
sendMessage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendMessageActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(inputMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sendMessage))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(status, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(connectToServer))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(privateConnection)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(status)
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(connectToServer)
.addComponent(privateConnection))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(sendMessage, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(inputMessage, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void connectToServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectToServerActionPerformed
}//GEN-LAST:event_connectToServerActionPerformed
private void sendMessage(){
Thread sendMessage = new Thread(new Runnable() {
@Override
public void run() {
while(true){
String message = scan.nextLine();
try{
output.writeUTF(message);
}catch(IOException ex){
log("writeMessageThread : " + ex.getMessage());
}
}
}
});
sendMessage.start();
}
private void sendMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendMessageActionPerformed
sendMessage();
}
private void readMessage(){ //needs to implement the message area
Thread readMessage = new Thread(new Runnable() {
@Override
public void run() {
while(true){
try{
String message = input.readUTF();
log(message);
}catch(IOException ex){
log("readMessageThread : " + ex.getMessage());
}
}
}
});
readMessage.start();
}
private void log(String message){
System.out.println(message);
}//GEN-LAST:event_sendMessageActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
chatClient client = new chatClient();
client.readMessage();
client.sendMessage();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new chatClient().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton connectToServer;
private java.awt.TextField inputMessage;
private javax.swing.JScrollPane jScrollPane1;
private static javax.swing.JTextArea messageArea;
private javax.swing.JButton privateConnection;
private javax.swing.JButton sendMessage;
private javax.swing.JLabel status;
// End of variables declaration//GEN-END:variables
}
服务器
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import static java.rmi.server.LogStream.log;
import java.util.ArrayList;
import java.util.List;
public class chatServer extends javax.swing.JFrame {
/**
* Creates new form chatServer
*/
static List<ClientHandler> clients;
ServerSocket serverSocket;
static int usersOnline = 0;
Socket socket;
public chatServer() {
clients = new ArrayList<>();
try{
serverSocket = new ServerSocket(Constants.PORT);
}catch(IOException ex) {
log("Server : " + ex.getMessage());
}
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
messageArea = new javax.swing.JTextArea();
jLabel3 = new javax.swing.JLabel();
inputMessage = new java.awt.TextField();
sendMessage = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("IP address:");
jButton1.setText("Start Server");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel2.setText("Users logged in:");
messageArea.setColumns(20);
messageArea.setRows(5);
jScrollPane1.setViewportView(messageArea);
jLabel3.setText("Server side");
inputMessage.setText("textField1");
inputMessage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
inputMessageActionPerformed(evt);
}
});
sendMessage.setText("Send");
sendMessage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendMessageActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(sendMessage)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(45, 45, 45))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addComponent(jLabel1))))
.addGap(82, 82, 82))
.addGroup(layout.createSequentialGroup()
.addComponent(inputMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(323, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(inputMessage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(sendMessage))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void inputMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inputMessageActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_inputMessageActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void sendMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendMessageActionPerformed
}//GEN-LAST:event_sendMessageActionPerformed
public static void main(String args[]) {
chatServer server = new chatServer();
server.waitingForConnection();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new chatServer().setVisible(true);
}
});
}
/* Create and display the form */
private void waitingForConnection(){
log("Server running...");
while(true) {
try{
socket = serverSocket.accept();
}catch(IOException ex) {
log("Waiting for connection : " + ex.getMessage());
}
log("Client accepted the connection : " + socket.getInetAddress());
usersOnline++;
ClientHandler handler = new ClientHandler(socket, "User" + usersOnline);
Thread thread = new Thread(handler);
addClient(handler);
thread.start();
}
}
public static List<ClientHandler> getClients(){
return clients;
}
private void addClient(ClientHandler client){
clients.add(client);
}
private void log(String message){
System.out.println(message);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private java.awt.TextField inputMessage;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private static javax.swing.JTextArea messageArea;
private javax.swing.JButton sendMessage;
// End of variables declaration//GEN-END:variables
}
登录
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chatroomcwk;
import static com.sun.org.apache.xalan.internal.lib.ExsltDynamic.map;
import java.util.*;
import java.lang.*;
import java.awt.Component;
import java.awt.Frame;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class login extends javax.swing.JFrame {
/**
* Creates new form login
*/
public login() {
initComponents();
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
passwordText = new javax.swing.JPasswordField();
userText = new java.awt.TextField();
jLabel3 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
status = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Username:");
jLabel2.setText("Password:");
passwordText.setText("");
passwordText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
passwordTextActionPerformed(evt);
}
});
userText.setText("");
userText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
userTextActionPerformed(evt);
}
});
jLabel3.setText("Login Page");
jButton2.setText("Sign in");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
status.setText("Status");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(91, 91, 91))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel4)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(userText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(passwordText, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)))))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(status)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 130, Short.MAX_VALUE)
.addComponent(jButton2)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(jLabel3)
.addGap(45, 45, 45)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(userText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(passwordText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 166, Short.MAX_VALUE)
.addComponent(jLabel4)
.addGap(9, 9, 9)
.addComponent(jButton2)
.addGap(21, 21, 21))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(status)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void passwordTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passwordTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_passwordTextActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
String username = userText.getText();
String password = passwordText.getText();
Component frame = null;
//Create a map for users where put username as key and password as value
Map<String, String> usersMap = new HashMap<>();
usersMap.put("user1", "password1");
usersMap.put("user2", "password2");
//Create a map for the admin where put username as key and password as value
Map<String, String> adminMap = new HashMap<>();
adminMap.put("Admin", "password");
// Implement your authentication
if(usersMap.get(username) != null){
JOptionPane.showMessageDialog(frame, "You are successfully logged in!");
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
chatClient second = new chatClient();
second.setVisible(true); //displays the client page
} else if (adminMap.get(username) != null){
JOptionPane.showMessageDialog(frame, "You are successfully logged in!");
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
chatServer third = new chatServer();
third.setVisible(true); //displays the server page
}else if (password.equals(map.usermap.get(username))){
JOptionPane.showMessageDialog(frame, "You are successfully logged in!");
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
chatServer third = new chatServer();
third.setVisible(true); //displays the server page
}
else {
status.setText("Invalid username or password entered");
}
}//GEN-LAST:event_jButton2ActionPerformed
private void userTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_userTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_userTextActionPerformed
/**
* @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
*/
HashMap<String, String> users = new HashMap<String, String>();
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//GEN-BEGIN:variables
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private static javax.swing.JPasswordField passwordText;
private javax.swing.JLabel status;
private static java.awt.TextField userText;
// End of variables declaration//GEN-END:variables
}
Map
import java.util.HashMap;
import java.util.Map;
public class map {
public static HashMap<String, String> usermap = new HashMap<>();
public HashMap<String, String> getUsers()
{
return usermap;
}
}
1条答案
按热度按时间h79rfbju1#
如评论中所述,您创建的对象太多。例如,请查看下面代码中的标记行:
在第(a)行中,您创建了一个新的chatserver对象(为了符合java命名约定,应该将其重新命名为chatserver),然后让这个对象等待swing事件线程的连接,。。。好的。
但是在第(b)行中,您创建了一个全新的chatserver对象,并将其显示为chatservergui。但是这个对象与第(a)行中创建的对象完全不同,第一个对象发生的状态更改不会反映在第二个对象上,反之亦然,这意味着gui将完全不知道任何聊天连接,这是不好的。
相反,您应该创建一个chatserver对象,让它等待连接并显示它。比如说:
同样的问题(和解决方案)也适用于聊天客户端。
请注意,如果这是我的程序,我会将类重命名为chatserver,并为等待的连接创建一个明确的线程。比如: