I really dont know if how am I going to display this in my application since I just coudln't figure out if what is the exact code that i will going to use. I'm making a simple chat client server where two or more clients can chat with each other with the help of input/output streams and serversocket. what i want to do is that after a person can login it will pop up a message in JtextArea saying that a particular person is online and if the person closes the application, a message will be send to other client saying that a particular person is offline.
this is the code for ChatClient which will display a JtextArea for diplaying a mesage, JtextField for typing a message and a JButton for sending a message to the sender going back to the clients.
JTextArea incoming;
JTextArea outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
static JFrame frame;
JButton send;
JPanel mainPanel;
static String userName;
public void createAndShowGUI(){
frame = new JFrame("chat client");
mainPanel = new JPanel();
mainPanel.setBackground(new Color(53,53,53));
incoming = new JTextArea(15, 50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy (ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
//create GridBagLayout and GridBagConstraints for Layouting
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
//assign gbl inside componentPanel
mainPanel.setLayout(gbl);
//for layouting JTextArea
gbc.fill = GridBagConstraints.FIRST_LINE_START;
gbc.ipady = 0;
gbc.ipadx = 20;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.gridheight = 1;
//add labelLogin in componentPanel
gbl.setConstraints(qScroller, gbc);
mainPanel.add(qScroller);
//for layouting JTextField
outgoing = new JTextArea();
outgoing.setLineWrap(true);
outgoing.setWrapStyleWord(true);
JScrollPane oScroller = new JScrollPane(outgoing);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
oScroller.setPreferredSize(new Dimension(500,60));
gbc.fill = GridBagConstraints.FIRST_LINE_START;
gbc.ipady = 0;
gbc.ipadx = 20;
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 1;
gbc.gridheight = 0;
//add labelLogin in componentPanel
gbl.setConstraints(oScroller, gbc);
mainPanel.add(oScroller);
//instantiate JButton
send = new JButton("send");
send.addActionListener(new SendButtonListener());
send.setPreferredSize(new Dimension(48,60));
send.setBorder(BorderFactory.createEtchedBorder(1));
send.setBackground(new Color(248,181,63));
send.setFont(new Font("verdana",Font.BOLD,12));
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.ipady = 0;
gbc.ipadx = 20;
gbc.gridy = 5;
gbc.gridx = 1;
gbc.gridwidth = 2;
gbc.gridheight = 0;
gbl.setConstraints(send, gbc);
mainPanel.add(send);
setUpNetworking();
//confirmation();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
frame.add(mainPanel);
frame.setSize(605, 355);
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end createAndShowGUI
private void setUpNetworking() {
try {
sock = new Socket("00.000.00.00", 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("network established");
}
catch(IOException ex)
{
// ex.printStackTrace();
JOptionPane.showMessageDialog(null, "could not connect to server!","error", JOptionPane.ERROR_MESSAGE );
System.exit(0);
}
}
public String getUserName(){
return userName;
}
public void setUserName(String uname){
userName = uname;
}
//is this a right method...?
public void confirmation(){
writer.println(getUserName());
writer.flush();
//System.out.print(getUserName() + " is online " + "\n");
//incoming.append(getUserName() + " is online " + "\n");
}
public class SendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
writer.println(getUserName());
writer.print(" : ");
writer.println(outgoing.getText());
writer.flush();
}
catch (Exception ex) {
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
class IncomingReader implements Runnable {
LoginForm lf = new LoginForm();
public void run() {
String message;
String username;
try {
while ((username = reader.readLine()) != null) {
message = reader.readLine();
incoming.append(username + message + "\n");
//if else here?
}
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
public static void main(String [] args){
new ChatClient().createAndShowGUI();
}//end main
}//end class
below is the ChatServer where all the messages coming from the ChatClients sends to the ChatServer and send it back again so that all the clients will read the messages.
public class ChatServer {
String uname, userName, confirmation;
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSOcket) {
try {
sock = clientSOcket;
InputStreamReader isReader = new InputStreamReader(
sock.getInputStream());
reader = new BufferedReader(isReader);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void run() {
String message;
try {
// I wonder if the code below is right.?
confirmation = reader.readLine();
System.out.println(confirmation + " is online");
while ((userName = reader.readLine()) != null) {
message = reader.readLine();
// System.out.print(userName);
// System.out.print(message + "\n");
tellEveryone(userName);
tellEveryone(message);
}
} catch (Exception ex) {
System.out.println(confirmation + " is offline");
// System.out.println("connection reset!");
// ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new ChatServer().go();
}
public void go() {
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(5001);
while (true) {
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(
clientSocket.getOutputStream());
// writer.println(confirmation);
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}