Total members 11895 |It is currently Tue Dec 03, 2024 6:32 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





I have problem with my chatting application here. I made this using Netbeans and the problem i am facing is that if i sent multiline message to other clients, the other client only receive the first line i typed. The second and next lines are not sent. Honestly this code is not entirely mine since m still trying to make it as simple as posible as client-server introduction for myself. I would be very grateful if anybody could help me with this. Along i attach the chatting file.

Finished project could be found at :
finished-projects/java-chat-t644-20.html

java code
/*
* PubChat.java
*
* Created on April 10, 2009, 9:19 PM
*/

package ClientSidePckg;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.text.*;
import java.util.List;
import java.util.*;

import javax.swing.filechooser.*;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;


import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import static java.awt.event.KeyEvent.VK_ENTER;
import static java.awt.event.KeyEvent.VK_CONTROL;


public class PubChat extends javax.swing.JFrame implements ActionListener,

KeyListener, Runnable {
String clientName, serverName, clientGender, fromServer;
String newUserName, newUserGender;
Socket socket;
PrintStream ps;
BufferedReader br;
Thread thread;
StringTokenizer tokenizer;
int totalUserCount;
Vector userVector;
StringBuffer sb;
List<Integer> charsPressed;

private static final Integer VK_ENTR = new Integer(VK_ENTER);
private static final Integer VK_CTRL = new Integer(VK_CONTROL);
private static final JFileChooser fc = new JFileChooser();
private static final String txt = ".txt";

static {
fc.setAcceptAllFileFilterUsed(true);
}
private String newline = System.getProperty("line.separator");

/** Creates new Constructor PubChat */
public PubChat(String name, String servername, String gender) {
super("ChappyChat 1.1 Public Room for "+name);
initComponents();
setResizable(false);
setVisible(true);
txtAreaSend.requestFocus();

btnSend.addActionListener(this);
btnPrivate.addActionListener(this);
mnuItemDisconnect.addActionListener(this);
mnuItemAbout.addActionListener(this);
mnuItemLogin.addActionListener(this);
mnuItemQuit.addActionListener(this);
mnuItemSave.addActionListener(this);
txtAreaSend.addKeyListener(this);

addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent evt)
{
quitConnection("QUIT");
System.exit(0);
}
});

/*
txtAreaSend.setDocument(new PlainDocument() {
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (str.equals(VK_CONTROL + "\n"))
super.insertString(offs, "\n", a);
else if (!str.equals("\n"))
super.insertString(offs, str, a);
}
});
* */

charsPressed = new ArrayList<Integer>();

clientName = name;
serverName = servername;
clientGender = gender;
thread = new Thread(this);
userVector = new Vector(1,1);
try {
socket = new Socket(serverName,9999);
ps=new PrintStream(socket.getOutputStream());
br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
thread.start();
}
catch(IOException e) {
msgPaneArea.setText("Connection to server failed. Make sure the server name is valid.");
}
sendMsgToServer("#HELO"+clientName+"~"+clientGender);
}



/** 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.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

jLabel1 = new javax.swing.JLabel();
lblInfo = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
lstUser = new javax.swing.JList();
btnPrivate = new javax.swing.JButton();
btnSend = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
msgPaneArea = new javax.swing.JTextArea();
jScrollPane3 = new javax.swing.JScrollPane();
txtAreaSend = new javax.swing.JTextArea();
jMenuBar1 = new javax.swing.JMenuBar();
mnuFile = new javax.swing.JMenu();
mnuItemLogin = new javax.swing.JMenuItem();
mnuItemDisconnect = new javax.swing.JMenuItem();
mnuItemSave = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JSeparator();
mnuItemQuit = new javax.swing.JMenuItem();
mnuAbout = new javax.swing.JMenu();
mnuItemAbout = new javax.swing.JMenuItem();

jLabel1.setText("jLabel1");

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setIconImage(getIconImage());
setResizable(false);
getContentPane().setLayout(null);

lblInfo.setBackground(new java.awt.Color(102, 51, 0));
lblInfo.setFont(new java.awt.Font("Comic Sans MS", 1, 11));
lblInfo.setForeground(new java.awt.Color(255, 255, 255));
lblInfo.setOpaque(true);
getContentPane().add(lblInfo);
lblInfo.setBounds(0, 0, 690, 20);

jScrollPane2.setViewportView(lstUser);

getContentPane().add(jScrollPane2);
jScrollPane2.setBounds(560, 20, 130, 390);

btnPrivate.setText("Private");
getContentPane().add(btnPrivate);
btnPrivate.setBounds(560, 410, 130, 40);

btnSend.setText("Send");
btnSend.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSendActionPerformed(evt);
}
});
getContentPane().add(btnSend);
btnSend.setBounds(570, 470, 80, 50);

msgPaneArea.setColumns(20);
msgPaneArea.setEditable(false);
msgPaneArea.setRows(5);
jScrollPane1.setViewportView(msgPaneArea);

getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(0, 20, 560, 430);

txtAreaSend.setColumns(20);
txtAreaSend.setRows(5);
jScrollPane3.setViewportView(txtAreaSend);

getContentPane().add(jScrollPane3);
jScrollPane3.setBounds(0, 460, 550, 70);

mnuFile.setText("File");

mnuItemLogin.setText("Login");
mnuItemLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mnuItemLoginActionPerformed(evt);
}
});
mnuFile.add(mnuItemLogin);

mnuItemDisconnect.setText("Disconnect");
mnuItemDisconnect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mnuItemDisconnectActionPerformed(evt);
}
});
mnuFile.add(mnuItemDisconnect);

mnuItemSave.setText("Save");
mnuFile.add(mnuItemSave);
mnuFile.add(jSeparator1);

mnuItemQuit.setLabel("Quit");
mnuFile.add(mnuItemQuit);

jMenuBar1.add(mnuFile);

mnuAbout.setText("About");

mnuItemAbout.setLabel("About ChappyChat 1.1");
mnuAbout.add(mnuItemAbout);

jMenuBar1.add(mnuAbout);

setJMenuBar(jMenuBar1);

java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-697)/2, (screenSize.height-597)/2, 697, 597);
}// </editor-fold>//GEN-END:initComponents




private void mnuItemDisconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuItemDisconnectActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_mnuItemDisconnectActionPerformed

private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnSendActionPerformed

private void mnuItemLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuItemLoginActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_mnuItemLoginActionPerformed

/**
* @param args the command line arguments
*/

public static void main(String args[]) {
//java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
// new PubChat().setVisible(true);
// }
// });
//new PrivChat(clientName);
}

// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnPrivate;
private javax.swing.JButton btnSend;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel lblInfo;
private javax.swing.JList lstUser;
private javax.swing.JMenu mnuAbout;
private javax.swing.JMenu mnuFile;
private javax.swing.JMenuItem mnuItemAbout;
private javax.swing.JMenuItem mnuItemDisconnect;
private javax.swing.JMenuItem mnuItemLogin;
private javax.swing.JMenuItem mnuItemQuit;
private javax.swing.JMenuItem mnuItemSave;
private javax.swing.JTextArea msgPaneArea;
private javax.swing.JTextArea txtAreaSend;
// End of variables declaration//GEN-END:variables



public void actionPerformed(ActionEvent e) {
Object button = e.getSource();
if (button == mnuItemQuit) {
quitConnection("QUIT");
System.exit(0);
}
if (button == mnuItemDisconnect) {
msgPaneArea.append("Connection to server has been disconnected...");
quitConnection("QUIT");
}
if(button == mnuItemLogin) {
quitConnection("QUIT");
setVisible(false);
new LoginChat();
}
if(button == mnuItemSave){
SaveListener();
}

if(button == mnuItemAbout) {
new About();
}
if(button == btnSend){
sendMessage();
txtAreaSend.setText("");
txtAreaSend.requestFocus();
}
if(button == btnPrivate) {
if(lstUser.getSelectedValue()== null)
{
JOptionPane.showMessageDialog(null,"Select a user first!");
return;
}
if(lstUser.getSelectedValue().toString().equals(clientName))
{
JOptionPane.showMessageDialog(null,"You can't select yourself!");
return;
}
sendPrivateMessage(txtAreaSend.getText(), lstUser.getSelectedValue().toString());
txtAreaSend.setText("");
}
}
protected void SentPrivateMessageToServer(String Message, String ToUserName) {
sendMsgToServer("PRIV "+ToUserName+"~"+clientName+":"+Message);
msgPaneArea.append(ToUserName + ":" + Message+"\n");
}
public void keyTyped(KeyEvent e) {}

public void keyPressed(KeyEvent e) {

if (e.getSource() == txtAreaSend) {
charsPressed.add(e.getKeyCode());

if (charsPressed.contains(VK_ENTER)) {
if (charsPressed.contains(VK_CTRL))
txtAreaSend.append("\n");
else {
sendMessage();
txtAreaSend.requestFocus();
}
}
}

/*
if(e.getKeyCode() != 10){
//
}
else{
if(e.isControlDown() && e.getKeyCode() == 10){
String strBefore = txtAreaSend.getText();
txtAreaSend.setText(strBefore+"\n");
}
else if (e.getKeyCode() == 10) {
sendMessage();
//msgPaneArea.append(txtAreaSend.getText());
txtAreaSend.setText("");
int caretPosition = txtAreaSend.getCaretPosition()-1;
txtAreaSend.setCaretPosition(caretPosition);
}
}
*/
}

public void keyReleased(KeyEvent e) {

if (e.getSource() == txtAreaSend) {

if (charsPressed.contains(VK_ENTR) && !charsPressed.contains(VK_CTRL))
txtAreaSend.setText("");

for (ListIterator<? extends Integer> it = charsPressed.listIterator(); it.hasNext(); ) {
Integer keyPressed = it.next();
if (keyPressed.intValue() == e.getKeyCode()) it.remove();
}

}

}

public void run() {
while (thread != null){
try {
fromServer = br.readLine();
if (fromServer.startsWith("ADD ")) {
totalUserCount++;
String newUser = fromServer.substring(4);
userVector.addElement(newUser);
lstUser.setListData(userVector);
msgPaneArea.append(newUser + " joins ChappyChat 1.1...\n");
updateInfo();
}
if (fromServer.startsWith("MESS")) {
String clientSender = fromServer.substring(4, fromServer.indexOf(":"));
String message = fromServer.substring(fromServer.indexOf(":")+1);
msgPaneArea.append(clientSender+": "+message+"\n");
}
if (fromServer.startsWith("KICK")) {
msgPaneArea.append("YOU'VE BEEN KICKED BY THE ADMINISTRATOR FOR FLOODING MESSAGE\n");
quitConnection("KICK");
thread = null;
}
if(fromServer.startsWith("LIST")) {
tokenizer = new StringTokenizer(fromServer.substring(5),";");
totalUserCount = tokenizer.countTokens();
while(tokenizer.hasMoreTokens())
{
userVector.addElement(tokenizer.nextToken());
}
lstUser.setListData(userVector);
msgPaneArea.append("Welcome to ChappyChat 1.1 \n");
updateInfo();
}

//ini perlu di rehab...kan buka jendela baru :-?
if(fromServer.startsWith("PRIVA")) {
String clientSender = fromServer.substring(5,fromServer.indexOf(":"));
String message = fromServer.substring(fromServer.indexOf(":")+1);
msgPaneArea.append("Private message from "+clientSender+" : "+ message+"\n");
}
if(fromServer.startsWith("REMO")) {
String clientRemove = fromServer.substring(4);
msgPaneArea.append(clientRemove+" has logged out from ChappyChat 1.1\n");
totalUserCount--;
updateInfo();
userVector.remove(clientRemove);
lstUser.setListData(userVector);
}
if(fromServer.startsWith("INKI")) {
String clientKicked = fromServer.substring(4);
msgPaneArea.append(clientKicked+" has been kicked out form ChappyChat 1.1\n");
totalUserCount--;
updateInfo();
userVector.remove(clientKicked);
lstUser.setListData(userVector);
}
//perlu ga? soalnya kan uda ada di add :-?
if(fromServer.startsWith("JOIN ")) {
msgPaneArea.append(fromServer.substring(5)+" joins ChappyChat1.1\n");
totalUserCount++;
userVector.addElement(fromServer.substring(5));
lstUser.setListData(userVector);
updateInfo();
}
if(fromServer.startsWith("DETA "))
{
newUserName = fromServer.substring(5,fromServer.indexOf("~"));
newUserGender=fromServer.substring(fromServer.indexOf("~")+1);
}
}
catch(IOException e) {}
}
}

private void quitConnection(String tipe) {
if(socket!=null)
{
try
{
if (tipe.equals("QUIT"))
sendMsgToServer("#QUIT"+clientName);
if(tipe.equals("KICK"))
sendMsgToServer("#KICK"+clientName);
socket.close();
socket = null;
}
catch(IOException e) {}
}
if (thread!=null)
{
thread.stop();
thread = null;
}
}

private void sendMessage() {
sendMsgToServer("#MESS"+clientName+":"+txtAreaSend.getText());
msgPaneArea.append(clientName+":"+txtAreaSend.getText()+"\n");
}

private void sendMsgToServer(String msg) {
ps.println(msg);
}

private void sendPrivateMessage(String msg, String toClient) {
sendMsgToServer("#PRIV"+toClient+"~"+clientName + ":" + msg);
msgPaneArea.append("(Private Chat With " + toClient + "): " + msg + "\n");
}

private void updateInfo() {
sb = new StringBuffer();
sb.append(totalUserCount);
lblInfo.setText("Total User(s) : " + sb.toString());
}



protected Frame getFrame() {
for (Container p = getParent(); p != null; p = p.getParent())
if (p instanceof Frame)
return (Frame) p;
return null;
}


public void SaveListener(){
int returnVal = fc.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (file.exists()) {
//default icon, custom title
int n = JOptionPane.showConfirmDialog(
getFrame(),
"File already exists. Would you like to override it?",
"Override File?",
JOptionPane.YES_NO_OPTION);

if (n == JOptionPane.NO_OPTION) {
//log.append("Save command cancelled by user. User do not wish to override it." + newline); //Display this command in the text area
JOptionPane.showMessageDialog(getFrame(),"Save command cancelled by user. User do not wish to override it.");
return;
}
} //end of if (file.exists())
boolean isAcceptedExtension = fc.accept(file);

if (!isAcceptedExtension) {
//Custom button text
Object[] options = {"Yes, please",
"No, thanks",
"Don't do anything"};
int n = JOptionPane.showOptionDialog(getFrame(),
"The file name does not have '.txt' extension.\n\n"
+ "Would you like the program to append '.txt' to the filename on behalf of you?\n\n"
+ String.format("<html><body>Changing filename from

<span style='font-family: monospace'><font color=#ff0000>'%s'</font>

to <font color=#ff0000>'%s.txt'</font></span></body></html>\n", file.getPath(), file.getPath()),

"A Confirmation Question",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);


if (n == JOptionPane.YES_OPTION) {
file = makeTxt(file);
isAcceptedExtension = true;
}
} //end of if (!isAcceptedExtension)
if (isAcceptedExtension) {
Thread saver = new FileSaver(file, msgPaneArea.getDocument());
saver.start();

//log.append("Saving: " + file.getName() + "." + newline); //Display "Saving" and the retrieved file name in the text area
JOptionPane.showMessageDialog(getFrame(),"Saving : " + file.getName() + ".");
} else
//log.append("Saving Failed: " + file.getName() + " does not END with (.txt)." + newline);
//Display "Saving" and the retrieved file name in the text area
JOptionPane.showMessageDialog(getFrame(),"Saving Failed....");
} else
txtAreaSend.append("Save command cancelled by user." + newline); //Display this command in the text area
}


/**
* Thread to save a document to file
*/




/**
* Changed the extension to .txt if it has not done.
*
* @param f file to be changed.
* @return File that has been changed.
*/
private File makeTxt(File f) {
return (f.getName().endsWith(txt)) ? f : new File(f.getName().concat(txt));
}
class FileSaver extends Thread {
private Document doc;
private File f;
private static final String txt = ".txt";


FileSaver(File f, Document doc) {
setPriority(4);
this.f = makeTxt(f);
this.doc = doc;
}

@Override
public void run() {
JComponent status = new JPanel();
JFrame frame = new JFrame("Saving...");
try {

// initialize the statusbar
status.removeAll();
JProgressBar progress = new JProgressBar();
progress.setMinimum(0);
progress.setMaximum((int) doc.getLength());
status.add(progress);
status.revalidate();

Container c = frame.getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.PAGE_AXIS));
c.add(status);
c.add(new JLabel(String.format("Saving file '%s' in '%s'", f.getName(), f.getPath())));
c.add(new JLabel("Please wait..."));

frame.pack();
frame.setVisible(true);
halt(2000);

// start writing
Writer out = new FileWriter(f);
Segment text = new Segment();
text.setPartialReturn(true);
int charsLeft = doc.getLength();
int offset = 0;
while (charsLeft > 0) {
doc.getText(offset, Math.min(4096, charsLeft), text);
out.write(text.array, text.offset, text.count);
charsLeft -= text.count;
offset += text.count;
progress.setValue(offset);
halt(10);
}
out.flush();
out.close();
} catch (IOException e) {
final String msg = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(getFrame(),
"Could not save file: " + msg,
"Error saving file",
JOptionPane.ERROR_MESSAGE);
}
});
} catch (BadLocationException e) {
System.err.println(e.getMessage());
}
// we are done... get rid of progressbar
status.removeAll();
status.revalidate();
halt(2000);
frame.setVisible(false);
}
} // end of class FileSaver
private static final void halt(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException exception) {
System.err.println("Thread had been interrupted...");
}
}
} // end of class PubChat





Attachments:
File comment: Chatting Application File Using Java
myChat.rar [294.26 KiB]
Downloaded 759 times
Author:
Newbie
User avatar Posts: 16
Have thanks: 0 time
Post new topic Reply to topic  [ 1 post ] 

  Related Posts  to : Need help about chatting application i made...
 Need help in Chatting Program     -  
 Connecting Java Application to C++ Application from Code     -  
 HTML Form i made     -  
 Servelt Hello world I made by myself     -  
 Get address of the page from which the request was made     -  
 First Application in c#     -  
 want to develop an application of my own     -  
 Mobile Application     -  
 I need chat application using php     -  
 About Mobile application     -  









Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com