我在java中构建了一个小程序,用于从数据库中获取IP地址,然后调用新的JFrame(客户端)向服务器发送请求。我的问题是当我运行服务器(JFrame)和客户端(也是JFrame)。另外它们完美地工作,但是当我从包含带有数据的Jtable的另一个JFrame调用客户端时,通过单击按钮,客户端JFrame出现但接受只发送一条消息,并且不能接收服务器响应,除非我关闭了服务器。任何人都可以帮助我吗?
这是我的代码:
客户:
/*
* 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 Machine;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
/**
*
* @author Win
*/
public class Clio extends javax.swing.JFrame {
/**
* Creates new form Clio
*/
public String adresse = "192.168.10.139";
static Socket s;
static DataInputStream dun;
static DataOutputStream dout;
public Clio() {
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">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
msg_area = new javax.swing.JTextArea();
msg_text = new javax.swing.JTextField();
msg_send = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
msg_area.setColumns(20);
msg_area.setRows(5);
jScrollPane1.setViewportView(msg_area);
msg_text.setText("jTextField1");
msg_send.setText("Send Trans");
msg_send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
msg_sendActionPerformed(evt);
}
});
jButton1.setText("Refresh Connection");
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, 304, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(msg_send, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(msg_send)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)))
.addContainerGap(21, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void msg_sendActionPerformed(java.awt.event.ActionEvent evt) {
try {
String msgout = "";
msgout = msg_text.getText().trim();
dout.writeUTF(msgout);
} catch (Exception e) {
}
}
/**
* @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(Clio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Clio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Clio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Clio.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 Clio().setVisible(true);
}
});
try{
s = new Socket("localhost", 80);
dun = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
String msgin = "";
while(!msgin.equals("Exit")){
msgin = dun.readUTF();
msg_area.setText(msg_area.getText().trim()+"\n serveur :\t"+msgin);
}
}catch(Exception e){}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private static javax.swing.JTextArea msg_area;
private javax.swing.JButton msg_send;
private javax.swing.JTextField msg_text;
// End of variables declaration
}
服务器:
/*
* 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 Machine;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Win
*/
public class Serveur extends javax.swing.JFrame {
/**
* Creates new form Interface
*/
static ServerSocket ss;
static Socket s;
static DataInputStream dun;
static DataOutputStream dout;
public Serveur() {
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">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
msg_area = new javax.swing.JTextArea();
msg_text = new javax.swing.JTextField();
msg_send = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
msg_area.setColumns(20);
msg_area.setRows(5);
jScrollPane1.setViewportView(msg_area);
msg_text.setText("jTextField1");
msg_send.setText("jButton1");
msg_send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
msg_sendActionPerformed(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, 336, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(msg_send)))
.addContainerGap(25, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(msg_send))
.addContainerGap(21, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void msg_sendActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
String msgout = "";
msgout = msg_text.getText().trim();
dout.writeUTF(msgout);
} catch (Exception e) {
}
}
/**
* @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(Serveur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Serveur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Serveur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Serveur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Serveur().setVisible(true);
}
});
String msgin = "";
try{
ss = new ServerSocket(80);
s = ss.accept();
dun = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
while(!msgin.equals("Exit")){
msgin = dun.readUTF();
msg_area.setText(msg_area.getText().trim()+"\n"+msgin);
}
}catch(Exception e){}
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private static javax.swing.JTextArea msg_area;
private javax.swing.JButton msg_send;
private javax.swing.JTextField msg_text;
// End of variables declaration
}
将调用客户端JFrame的表JFrame
/*
* 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 Java;
import Machine.Clio;
import java.awt.event.KeyEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
/**
*
* @author Win
*/
public class Call_Transfo extends javax.swing.JFrame {
/**
* Creates new form Call_Transfo
*/
public Call_Transfo() {
initComponents();
Show_Users_In_Jtable();
}
public void Clio(){
Socket s= new Socket();
DataInputStream dun;
DataOutputStream dout;
String msgout = "";
String msgin = "";
try{
s = new Socket("localhost", 80);
dun = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
msgout = jTextField2.getText().trim();
dout.writeUTF(msgout);
msgin = dun.readUTF();
jTextField3.setText(jTextField3.getText().trim()+"\n serveur :\t"+msgin);
}catch(Exception e){}
}
public Connection getConnection(){
Connection con;
String ruta ="C:\\Users\\Win\\Documents\\NetBeansProjects\\Newapp\\test.sqlite";
try{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:"+ruta);
return con;
}catch(Exception e){e.printStackTrace(); return null;}
}
public ArrayList<User> getusersList(){
ArrayList<User> usersList = new ArrayList<User>();
Connection connection = getConnection();
String query = "Select * from users ";
Statement st;
ResultSet rs;
try{
st = connection.createStatement();
rs = st.executeQuery(query);
User user;
while(rs.next()){
user = new User(rs.getInt("id"),rs.getString("nom"), rs.getString("région"),rs.getString("adresse"));
usersList.add(user);
}
}catch(Exception e){e.printStackTrace();}
return usersList;
}
public void Show_Users_In_Jtable(){
ArrayList<User> list = getusersList();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
Object [] row = new Object[4];
for(int i =0; i<list.size();i++){
row[0] = list.get(i).getNom();
row[1] = list.get(i).getRégion();
row[2] = list.get(i).getAdresse();
model.addRow(row);
}
}
// Executer le SQL Query
public void executeSQLQuery(String query, String message){
Connection con = getConnection();
Statement st;
try{
st = con.createStatement();
if((st.executeUpdate(query)) == 1){
// Refresh jtable Data
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setRowCount(0);
Show_Users_In_Jtable();
JOptionPane.showMessageDialog(null,"Data "+ message + " Successefuly");
}
else{
JOptionPane.showMessageDialog(null,"Data not "+message);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
/**
* 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() {
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jButton1.setFont(new java.awt.Font("Kalinga", 0, 14)); // NOI18N
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Java/wifi-icon (1).png"))); // NOI18N
jButton1.setText("Appeler");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 130, 120, 30));
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jPanel1.add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 70, 120, 30));
jPanel1.add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 160, 210, 80));
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jPanel1.add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 100, 120, 30));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Transfo", "Région", "Adresse"
}
));
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTable1KeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
jTable1KeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTable1KeyTyped(evt);
}
});
jScrollPane1.setViewportView(jTable1);
jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, 330, 90));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Java/Neiige.png"))); // NOI18N
jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
int i = jTable1.getSelectedRow();
TableModel model = jTable1.getModel();
jTextField1.setText(model.getValueAt(i,0).toString());
jTextField2.setText(model.getValueAt(i,2).toString());
}
private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {
}
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTable1KeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}
private void jTable1KeyReleased(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == KeyEvent.VK_DOWN){
int i = jTable1.getSelectedRow();
TableModel model = jTable1.getModel();
jTextField1.setText(model.getValueAt(i,0).toString());
jTextField2.setText(model.getValueAt(i,2).toString());}
if(evt.getKeyCode() == KeyEvent.VK_UP){
int i = jTable1.getSelectedRow();
TableModel model = jTable1.getModel();
jTextField1.setText(model.getValueAt(i,0).toString());
jTextField2.setText(model.getValueAt(i,2).toString());}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Clio Cl = new Clio();
Cl.validate();
Cl.setVisible(true);
}
/**
* @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(Call_Transfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Call_Transfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Call_Transfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Call_Transfo.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 Call_Transfo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
// End of variables declaration
}