Skip to content

Instantly share code, notes, and snippets.

Created April 28, 2012 06:52
Show Gist options
  • Save anonymous/2516636 to your computer and use it in GitHub Desktop.
Save anonymous/2516636 to your computer and use it in GitHub Desktop.
TCP chat client
package chatclient;
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatMain extends javax.swing.JFrame {
String username;
Socket sock;
BufferedReader reader;
PrintWriter writer;
ArrayList<String> userList = new ArrayList();
Boolean isConnected = false;
/** Creates new form Chat */
public ChatMain() {
initComponents();
}
public class IncomingReader implements Runnable{
public void run() {
String stream;
String[] data;
String done = "Done", connect = "Connect", disconnect = "Disconnect", chat = "Chat";
try {
while ((stream = reader.readLine()) != null) {
data = stream.split("¥");
if (data[2].equals(chat)) {
chatTextArea.append(data[0] + ": " + data[1] + "\n");
} else if (data[2].equals(connect)){
chatTextArea.removeAll();
userAdd(data[0]);
} else if (data[2].equals(disconnect)) {
userRemove(data[0]);
} else if (data[2].equals(done)) {
usersList.setText("");
writeUsers();
userList.clear();
}
}
}catch(Exception ex) {
}
}
}
public void ListenThread() {
Thread IncomingReader = new Thread(new ChatMain.IncomingReader());
IncomingReader.start();
}
public void userAdd(String data) {
userList.add(data);
}
public void userRemove(String data) {
chatTextArea.append(data + " has disconnected.\n");
}
public void writeUsers() {
String[] tempList = new String[(userList.size())];
userList.toArray(tempList);
for (String token:tempList) {
usersList.append(token + "\n");
}
}
public void sendDisconnect() {
String bye = (username + "¥ ¥Disconnect");
try{
writer.println(bye); // Sends server the disconnect signal.
writer.flush(); // flushes the buffer
} catch (Exception e) {
chatTextArea.append("Could not send Disconnect message.\n");
}
}
public void Disconnect() {
try {
chatTextArea.append("Disconnected.\n");
sock.close();
} catch(Exception ex) {
chatTextArea.append("Failed to disconnect. \n");
}
isConnected = false;
usernameField.setEditable(true);
usersList.setText("");
}
/** 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();
usernameField = new javax.swing.JTextField();
connectButton = new javax.swing.JButton();
disconnectButton = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
usersList = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
chatTextArea = new javax.swing.JTextArea();
jScrollPane3 = new javax.swing.JScrollPane();
inputTextArea = new javax.swing.JTextArea();
sendButton = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("TCP Chat - Charlie Jason Jayme Zach");
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Enter Your Username:");
usernameField.setBackground(new java.awt.Color(204, 204, 255));
usernameField.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
connectButton.setText("Connect");
connectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
connectButtonActionPerformed(evt);
}
});
disconnectButton.setText("Disconnect");
disconnectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
disconnectButtonActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Users Connected:");
usersList.setBackground(new java.awt.Color(204, 255, 204));
usersList.setColumns(20);
usersList.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
usersList.setLineWrap(true);
usersList.setRows(5);
jScrollPane1.setViewportView(usersList);
chatTextArea.setBackground(new java.awt.Color(204, 255, 255));
chatTextArea.setColumns(20);
chatTextArea.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
chatTextArea.setLineWrap(true);
chatTextArea.setRows(5);
jScrollPane2.setViewportView(chatTextArea);
inputTextArea.setBackground(new java.awt.Color(204, 204, 255));
inputTextArea.setColumns(20);
inputTextArea.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
inputTextArea.setLineWrap(true);
inputTextArea.setRows(5);
jScrollPane3.setViewportView(inputTextArea);
sendButton.setText("Send");
sendButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendButtonActionPerformed(evt);
}
});
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/chatclient/images/awesome4.png"))); // NOI18N
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(layout.createSequentialGroup()
.addGap(55, 55, 55)
.addComponent(jLabel3)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(connectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(disconnectButton))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(connectButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(disconnectButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane3)
.addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 419, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}// </editor-fold>
private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (isConnected == false) {
username = usernameField.getText();
usernameField.setEditable(false);
try {
sock = new Socket("127.0.0.1", 5000);
InputStreamReader streamreader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamreader);
writer = new PrintWriter(sock.getOutputStream());
writer.println(username + "¥has connected.¥Connect"); // Displays to everyone that user connected.
writer.flush(); // flushes the buffer
isConnected = true; // Used to see if the client is connected.
} catch (Exception ex) {
chatTextArea.append("Cannot Connect! Try Again. \n");
usernameField.setEditable(true);
}
ListenThread();
} else if (isConnected == true) {
chatTextArea.append("You are already connected. \n");
}
}
private void disconnectButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
sendDisconnect();
Disconnect();
}
private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String nothing = "";
if ((inputTextArea.getText()).equals(nothing)) {
inputTextArea.setText("");
inputTextArea.requestFocus();
} else {
try {
writer.println(username + "¥" + inputTextArea.getText() + "¥" + "Chat");
writer.flush(); // flushes the buffer
} catch (Exception ex) {
chatTextArea.append("Message was not sent. \n");
}
inputTextArea.setText("");
inputTextArea.requestFocus();
}
inputTextArea.setText("");
inputTextArea.requestFocus();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChatMain().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextArea chatTextArea;
private javax.swing.JButton connectButton;
private javax.swing.JButton disconnectButton;
private javax.swing.JTextArea inputTextArea;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JButton sendButton;
private javax.swing.JTextField usernameField;
private javax.swing.JTextArea usersList;
// End of variables declaration
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment