2012-09-22 18 views
1

好吧,所以首先它連接到服務器,所以沒有問題的連接,下面的代碼顯示連接併發送消息到服務器,當我點擊運行它不開拓的JFrame的窗口,在這裏我可以看到我的工具...我也試着送什麼我從jMessage.getText進入OWS,但我在這條線得到一個錯誤:在Java中的TCP幾個問題

String process = jMessage.getText(); 

而且我想調用osw.write(process);只有當我點擊bSend按鈕時,那麼我怎樣才能在主要方法中使用它?請看看代碼,還記得第一個問題,我的JFrame在新窗口中打開不會顯示我,我的工具,它只是打印出的System.out.println在netbeans的控制檯:

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package tcpservidor; 

import java.io.*; 
import java.net.InetAddress; 
import java.net.Socket; 

/** 
* 
* @author Damage 
*/ 
public class TeKServer extends javax.swing.JFrame { 

/** 
* Creates new form TeKServer 
*/ 
public TeKServer() { 
    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() { 

    jLabel1 = new javax.swing.JLabel(); 
    jScrollPane1 = new javax.swing.JScrollPane(); 
    textArea = new javax.swing.JTextArea(); 
    jMessage = new javax.swing.JTextField(); 
    bSendMessage = new javax.swing.JButton(); 
    jLabel2 = new javax.swing.JLabel(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N 
    jLabel1.setText("Chat Client"); 

    textArea.setColumns(20); 
    textArea.setRows(5); 
    textArea.setEnabled(false); 
    jScrollPane1.setViewportView(textArea); 

    bSendMessage.setText("Send"); 
    bSendMessage.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      bSendMessageActionPerformed(evt); 
     } 
    }); 

    jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N 
    jLabel2.setText("Message"); 

    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() 
      .addGap(0, 0, Short.MAX_VALUE) 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
        .addComponent(jLabel1) 
        .addGap(294, 294, 294)) 
       .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
        .addComponent(jLabel2) 
        .addGap(303, 303, 303)))) 
     .addGroup(layout.createSequentialGroup() 
      .addContainerGap() 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(layout.createSequentialGroup() 
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
         .addComponent(jScrollPane1) 
         .addComponent(jMessage)) 
        .addContainerGap()) 
       .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
        .addGap(0, 291, Short.MAX_VALUE) 
        .addComponent(bSendMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) 
        .addGap(286, 286, 286)))) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addContainerGap() 
      .addComponent(jLabel1) 
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
      .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 319, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
      .addComponent(jLabel2) 
      .addGap(3, 3, 3) 
      .addComponent(jMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
      .addComponent(bSendMessage) 
      .addContainerGap()) 
    ); 

    pack(); 
}// </editor-fold> 

private void bSendMessageActionPerformed(java.awt.event.ActionEvent evt) { 
    // TODO add your handling code here: 


} 

/** 
* @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(TeKServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(TeKServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(TeKServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(TeKServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 
    /** Define a host server */ 
     String host = "192.168.0.8"; 
     /** Define a port */ 
     int port = 7777; 

     StringBuffer instr = new StringBuffer(); 
     String TimeStamp; 
     System.out.println("SocketClient initialized"); 
     try { 
     /** Obtain an address object of the server */ 
     InetAddress address = InetAddress.getByName(host); 
     /** Establish a socket connetion */ 
     Socket connection = new Socket(address, port); 
     System.out.println("Connection Established!"); 
     /** Instantiate a BufferedOutputStream object */ 
     BufferedOutputStream bos = new BufferedOutputStream(connection. 
     getOutputStream()); 

     /** Instantiate an OutputStreamWriter object with the optional character 
     * encoding. 
     */ 
     OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII"); 
     TimeStamp = new java.util.Date().toString(); 

     String process = jMessage.getText(); 
     /** Write across the socket connection and flush the buffer */ 
     osw.write(process); 
     osw.flush(); 
     /** Instantiate a BufferedInputStream object for reading 
     /** Instantiate a BufferedInputStream object for reading 
     * incoming socket streams. 
     */ 

     BufferedInputStream bis = new BufferedInputStream(connection. 
      getInputStream()); 
     /**Instantiate an InputStreamReader with the optional 
     * character encoding. 
     */ 

     InputStreamReader isr = new InputStreamReader(bis, "US-ASCII"); 

     /**Read the socket's InputStream and append to a StringBuffer */ 
     int c; 
     while ((c = isr.read()) != 13) 
      instr.append((char) c); 

     /** Close the socket connection. */ 
     connection.close(); 
     System.out.println(instr); 
     } 
     catch (IOException f) { 
     System.out.println("IOException: " + f); 
     } 
     catch (Exception g) { 
     System.out.println("Exception: " + g); 
     } 

    /* 
    * Create and display the form 
    */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 

     @Override 
     public void run() { 
      new TeKServer().setVisible(true); 
     } 
    }); 
} 
// Variables declaration - do not modify 
private javax.swing.JButton bSendMessage; 
private javax.swing.JLabel jLabel1; 
private javax.swing.JLabel jLabel2; 
public javax.swing.JTextField jMessage; 
private javax.swing.JScrollPane jScrollPane1; 
private javax.swing.JTextArea textArea; 
// End of variables declaration 
} 
+0

什麼問題? – EJP

回答

1

String process = jMessage.getText(); 

導致編譯錯誤,因爲它是在static main方法,其中jMessage是一個實例變量聲明。當您在main方法有大量的代碼,我會建議提取出來變成launchApp方法,並調用它像這樣:

new TeKServer().launchApp(); 

在新launchApp()方法,你將取代

java.awt.EventQueue.invokeLater(new Runnable() { 

    @Override 
    public void run() { 
     new TeKServer().setVisible(true); 
    } 
}); 

setVisible(true); 

我想打電話osw.write(處理);只有當我點擊按鈕BSEND

如果你想做到這一點,你可以保持osw作爲一個全球性的成員變量拿着插座打開的時間無限期地被一個壞的方法一般。建議只在需要時打開一個插座,寫入&關閉。

+0

我想每次點擊它時調用按鈕functoin,但這意味着我必須在bSendActionPerformed所在的位置編寫代碼,但這也意味着我必須在每次單擊它時打開套接字連接,然後關閉它。我這樣做,它只發送1消息,當按鈕被點擊時,它不發送更多的消息,儘管它必須再次運行bSendActionPerformed代碼並重新打開socken並再次聽我的消息,但它不這樣做,你會怎麼做在這種情況下建議? –

+0

這裏是我在這裏討論的代碼:http://pastebin.com/YEitj24s –