• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Multiple Client Chat server

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello friends i am developing Multiple user chat server

which has the following Client and Server Programs

all is working fine but message send by client should be echo to selected user but i am not getting so ...........

Please anyone help me out........

ChatClient.java

// Importing required packages.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

/*
<applet code="ChatClient" width=400 height=400>
</applet>
*/

public class ChatClient extends Applet implements ActionListener
{
// Declaration of variables
String cmdStr;
String currLogin;
String logMesg;
String serverMess;

StringTokenizer readTokenizer;

Label loginLabel;
Label currLoginLabel;

TextField loginText;
TextField chatMessage;

Button logonButton;
Button sendButton;

TextArea chatTextArea;
java.awt.List loginList;

Panel loginPanel;
Panel mainPanel;
Panel chatPanel;
Panel messagePanel;

CardLayout c1;

BufferedReader in;
PrintStream out;

Socket servSocket;

Thread listUpdateThread;

ListMesgUpdate listMesgObj ;
SendMessage sendMessageObj;

public void init()
{
// Initialize the input and output streams
try
{
servSocket = new Socket("127.0.0.1", 1313);
in = new BufferedReader
(new InputStreamReader(servSocket.getInputStream()));
out = new PrintStream (servSocket.getOutputStream());
}
catch (Exception Excep)
{
System.out.println("Socket error on client " + Excep);
}

c1 = new CardLayout();

// The applet has a border layout.
setLayout(new BorderLayout());

// The main panel of card layout is added to the applet panel.
mainPanel = new Panel();
add(mainPanel, BorderLayout.CENTER);

// Create all the panels needed
loginPanel = new Panel();
chatPanel = new Panel();
messagePanel = new Panel();

mainPanel.setLayout(c1);

//Add cards to the main panel
mainPanel.add("card1",loginPanel);
mainPanel.add("card2",chatPanel);

loginLabel = new Label("Login");
loginText = new TextField(30);
logonButton = new Button("LOGON");
loginList = new java.awt.List(10,true);
chatMessage = new TextField(30);
sendButton = new Button("SEND");

sendMessageObj = new SendMessage();
sendButton.addActionListener(sendMessageObj);


// Adding components to the Login Panel.
loginPanel.add(loginLabel);
loginPanel.add(loginText);
loginPanel.add(logonButton);

//Add panel to the center of the card layout
logonButton.addActionListener(this);

c1.show(mainPanel,"card1");

chatPanel.setLayout(new BorderLayout());
chatTextArea = new TextArea(20,20);
chatPanel.add(chatTextArea, BorderLayout.CENTER);
chatPanel.add(loginList, BorderLayout.EAST);
messagePanel.add(chatMessage);
messagePanel.add(sendButton);
chatPanel.add(messagePanel, BorderLayout.SOUTH);
}

// The implementation code for the actionPerformed method
public void actionPerformed(ActionEvent actEvt)
{
// Get the name of the client logged in.
currLogin = loginText.getText();

//Printing the logged in username on the command prompt
//in the server window
System.out.println("Currlogin is: " + currLogin);

logMesg = "Login:" + currLogin;
out.println(logMesg);
System.out.println("logMesg is: " + logMesg);

listMesgObj = new ListMesgUpdate();
listMesgObj.start();
}

// Displaying the name of the client who has logged out.
public void destroy()
{
logMesg = "Logout: " + currLogin;
out.println(logMesg);
}


class ListMesgUpdate extends Thread
{
public void run()
{
// Declaring variables.
String chatMessage;
String loginName;
String sender;

while (true)
{
try
{
serverMess = in.readLine();
}
catch (Exception Excep)
{
System.out.println(Excep);
}

readTokenizer = new StringTokenizer(serverMess, ":");

// Storing the information from the client
cmdStr = readTokenizer.nextToken();

// Incase of new client logged in.
if (cmdStr.equals("NewLogin"))
{
//Testing
//System.out.println("This is where all logins have been deleted");

//remove all the logged in members
loginList.removeAll();

// Add the login names to the Tokenizer.
while (readTokenizer.hasMoreTokens())
{
loginName = readTokenizer.nextToken();
loginList.add(loginName);
}
}

if (cmdStr.equals("NewLoginMess"))
{
while (readTokenizer.hasMoreTokens())
{
loginName = readTokenizer.nextToken();
chatTextArea.append(loginName + " has logged in\n" );
}
}

if (cmdStr.equals("DelLogin"))
{
loginList.removeAll();

while (readTokenizer.hasMoreTokens())
{
loginName = readTokenizer.nextToken();
loginList.add(loginName);
}
}

if (cmdStr.equals("DelLoginMess"))
{
while (readTokenizer.hasMoreTokens())
{
loginName = readTokenizer.nextToken();
chatTextArea.append("Good Bye " + loginName + " \n" );
}
}

if (cmdStr.equals("ChatMess"))
{
chatMessage = readTokenizer.nextToken();
sender = readTokenizer.nextToken();
chatTextArea.append(sender + " " + "says: "+ chatMessage + "\n");
}

c1.show(mainPanel,"card2");
} // End of while.
} // End of run()
}// End of class ListMesgUpdate

class SendMessage implements ActionListener
{
public void actionPerformed(ActionEvent actEvt)
{
//Testing
System.out.println(chatMessage.getText());

// Declaring variables.
String createMess;
String[] selectList = new String[10];
selectList = loginList.getSelectedItems();

//Testing
System.out.println(selectList.length);

if (selectList.length > 0)
{
createMess = "SendMessage: " + chatMessage.getText() +": "+ currLogin;

for (int i = 0; i < selectList.length; i++)
{
createMess += ": " ;
createMess += selectList[i];
}
out.println(createMess);
} // End of the if construct.
} // End of the method actionPerformed().
} // End of class SendMessage
} // End of the class ChatClient


ChatServer.java
import java.util.*;
import java.net.*;
import java.io.*;

public class ChatServer
{
// Declaration of variables
private ServerSocket serverSock;
private Socket fromClient;

private static Vector loginNames;
private static Vector loginSocks;

public ChatServer()
{
try
{
// Login names and sockets are stored in two vectors
loginNames = new Vector();
loginSocks = new Vector();
// Instantiating the ServerSocket object and passing the port number as an // argument
serverSock = new ServerSocket(1313);
}
catch (Exception Excep)
{
System.out.println("Server start problem "+ Excep);
}
System.out.println("Server Started");

while (true)
{
try
{
fromClient = serverSock.accept();
System.out.println("Server:Client connected");
Connect con = new Connect(fromClient);
}
catch (Exception Excep)
{
System.out.println("Accept problem "+ Excep);
}
}
}// End of the method ChatServer()

public static void main(String args[])
{
// Calling the Constructor ChatServer()
new ChatServer();

}// End of main()

// Start of class Connect
class Connect extends Thread
{
// Declaration of variables
Socket listClientSocket;
PrintStream outPrintStream;
String stringFromClient;
String currentLogin;
String delLogin;
String cmdStr;
StringTokenizer readTokenizer;
Iterator myIterator;
String tmpNameList;
String tmpName;
String tmpMesg;
Socket fromClient;
boolean threadOk=true;
private PrintStream out;
private BufferedReader in;

// Defining the constructor Connect() which accepts the sockets as the parameter
public Connect(Socket fromClient)
{
this.fromClient = fromClient;

try
{
// Opening an Output stream to send the output to the client
out = new PrintStream(fromClient.getOutputStream());
// Opening an Input stream to accept the input from the client
in = new BufferedReader(new InputStreamReader
(fromClient.getInputStream()));
}
catch (Exception Excep)
{
System.out.println("Stream error");
}
// Starting the current thread
this.start();
}

public void run()
{
System.out.println("Server:thread started for "+fromClient);

while (threadOk)
{
try
{
// Accepting the input from the client
stringFromClient = in.readLine();
System.out.println("Server:" +stringFromClient);
/* Storing the client input into a variable of type StringTokenizer with ":" as a separator */
readTokenizer = new StringTokenizer(stringFromClient,":");

// Moving to the next element
cmdStr = readTokenizer.nextToken();

// If a new client has logged in
if (cmdStr.equals("Login"))
{
/* Move to the next element and store the name of the person logged in */
currentLogin = readTokenizer.nextToken();

// Add the loginnames to the vector
loginNames.add(currentLogin);

// Add the socket to the vector
loginSocks.add(fromClient);

// Moving through the vector i.e. Login names
myIterator = loginNames.iterator();
tmpName = "NewLogin";
tmpMesg = "NewLoginMess:"+currentLogin;

while (myIterator.hasNext())
{
tmpName += ":";
tmpName += (String)myIterator.next();
}

myIterator = loginSocks.iterator();

// Moving through the vector LoginSocks
while (myIterator.hasNext())
{
listClientSocket = (Socket)myIterator.next();
outPrintStream = new PrintStream
(listClientSocket.getOutputStream());
/* Passing the information about the new person who has logged in and the message to the clients */
outPrintStream.println(tmpName);
outPrintStream.println(tmpMesg);
}
}

// If any client has logged out
if (cmdStr.equals("Logout"))
{
delLogin = readTokenizer.nextToken();
/* Storing the element number of the client who has logged out into a variable */
int vecIndex = loginNames.indexOf((Object)delLogin);
int curIndex = loginSocks.indexOf((Object)fromClient);

if (vecIndex == curIndex)
threadOk = false;
// Remove the logged out client from the vector
loginNames.removeElementAt(vecIndex);
loginSocks.removeElementAt(vecIndex);
myIterator = loginNames.iterator();
tmpName = "DelLogin";
tmpMesg = "DelLoginMess:"+delLogin;

while (myIterator.hasNext())
{
tmpName += ":";
tmpName += (String)myIterator.next();
}
myIterator = loginSocks.iterator();
/* Send the information of the logged out client to the other clients */
while (myIterator.hasNext())
{
listClientSocket = (Socket)myIterator.next();
outPrintStream = new PrintStream
(listClientSocket.getOutputStream());
outPrintStream.println(tmpName);
outPrintStream.println(tmpMesg);
}
}
// If any client wants to chat
if (cmdStr.equals("SendMessage"))
{
// Store the message of the client
String mesg = readTokenizer.nextToken();

// Store the message of the sender
String sender = readTokenizer.nextToken();
String receiver;
Socket sendToSocket;

// Send the message to all the clients
while (readTokenizer.hasMoreTokens())
{
receiver = readTokenizer.nextToken();
int vecIndex =loginNames.indexOf((Object)receiver);
sendToSocket =(Socket)loginSocks.elementAt(vecIndex);
outPrintStream = new PrintStream(
sendToSocket.getOutputStream());
outPrintStream.println("ChatMess:"+ mesg+":"+sender);
}
}
}
catch (Exception Excep)
{
System.out.println("Inputstream problem "+ Excep);
}
}
}
}//Connect()
}//Class ChatServer

 
Ranch Hand
Posts: 179
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I hardly doubt it that anyone would be interested in reading your code, by the way you presented it. Please edit it and usecodetags

Vishal
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic