Hello, I'm trying to make a chatting app just for educational purposes, to improve my skills and I got a question, or maybe a problem.
Look at the Code first:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* clientApp.java
*
* Created on Oct 22, 2011, 12:16:43 PM
*/
package networkingClient;
import com.sun.tools.javac.comp.Enter;
import java.awt.event.KeyEvent;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import quicktime.app.ui.PressActionButton;
/**
*
* @author Home
*/
public class clientApp extends javax.swing.JFrame {
Socket S;
DataOutputStream DOS;
String Message;
String Name;
public clientApp() {
initComponents();
// getConnection();
}
/** 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() {
txtSendMessage = new javax.swing.JTextField();
btnSendMessage = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
txtLog = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setName("Form"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(networkingServer.NetworkingApp.class).getContext().getResourceMap(clientApp.class);
txtSendMessage.setText(resourceMap.getString("txtSendMessage.text")); // NOI18N
txtSendMessage.setName("txtSendMessage"); // NOI18N
txtSendMessage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtSendMessageActionPerformed(evt);
}
});
txtSendMessage.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtSendMessageKeyTyped(evt);
}
public void keyPressed(java.awt.event.KeyEvent evt) {
txtSendMessageKeyPressed(evt);
}
});
btnSendMessage.setText(resourceMap.getString("btnSendMessage.text")); // NOI18N
btnSendMessage.setName("btnSendMessage"); // NOI18N
btnSendMessage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSendMessageActionPerformed(evt);
}
});
jScrollPane1.setName("jScrollPane1"); // NOI18N
txtLog.setColumns(20);
txtLog.setRows(5);
txtLog.setName("txtLog"); // NOI18N
jScrollPane1.setViewportView(txtLog);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
.add(layout.createSequentialGroup()
.add(txtSendMessage, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 269, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(btnSendMessage)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(txtSendMessage, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(btnSendMessage))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void btnSendMessageActionPerformed(java.awt.event.ActionEvent evt) {
try {
S = new Socket("192.168.1.2", 1234);
Message = txtSendMessage.getText();
DOS = new DataOutputStream(S.getOutputStream());
DOS.writeUTF(Message);
//DOS.flush();
//DOS.close();
txtSendMessage.setText("");
} catch (IOException ex) {
Logger.getLogger(clientApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void txtSendMessageKeyPressed(java.awt.event.KeyEvent evt) {
keyPressed(evt);
}
private void txtSendMessageKeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}
private void txtSendMessageActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* @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(clientApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(clientApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(clientApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(clientApp.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 clientApp().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnSendMessage;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea txtLog;
private javax.swing.JTextField txtSendMessage;
// End of variables declaration
public void getConnection() {
try {
S = new Socket("192.168.1.2", 1234);
// txtLog.append("Connected to: " + S.getLocalAddress() + " on Port: " + S.getLocalPort() + "\n");
} catch (UnknownHostException ex) {
txtLog.append("Error while connecting, please try again.");
} catch (IOException ex) {
txtLog.append("Error while connecting, please try again.");
}
}
public void connectionName()
{
Name = JOptionPane.showInputDialog("Please enter your Name");
}
public void sendMesage()
{
try {
S = new Socket("192.168.1.2", 1234);
Message = txtSendMessage.getText();
DOS = new DataOutputStream(S.getOutputStream());
DOS.writeUTF(Message);
//DOS.flush();
//DOS.close();
txtSendMessage.setText("");
} catch (IOException ex) {
Logger.getLogger(clientApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
;
sendMesage();
}
}
}
If you notice I have to repeat S = new Socket("IP", PORT) each time I send the message because if I left this line only in the getConnection() method it will just send one message and if I try to send another one, it will give errors.
My question is how to make the app connect only one time to the IP and port without using the line each time I send a message?
Note: ignore some of the useless code such as keyevent methods.
Thanks.