Solved

sample chat program

Posted on 2003-10-31
20
1,454 Views
Last Modified: 2008-02-26
Hi All,
I am looking for a simple sample java chat progam that will demonstrate the process and it works as a chat between 2 or more persons. Really bare bones.  Maybe using localhost as test url?

Delphi3.



 
0
Comment
Question by:delphi3
  • 8
  • 7
  • 4
  • +1
20 Comments
 
LVL 5

Accepted Solution

by:
lwinkenb earned 25 total points
Comment Utility
Here is probably the simplest example you can get of a client server chat.
http://pont.net/socket/java/
0
 
LVL 4

Author Comment

by:delphi3
Comment Utility
Nice hint for starters.

According to what I understand, a server is supposed to be a dummy. Right now it is, really dumb it can only listen. Right now the server with this arrangement (your gift) can only get message from one client at a time and display them in the System.out.println format in the server's display.

 

I know that I could broadcast from the server over "0.0.0.0"  and I could then "chat " with all the other clients that may be on the same "localhost" socket "1500" but it accepts only one connection at a time.
and it doesn't broadcast.

Do you have any help for  this idea?

As I stated in my initial request "it works as a chat between 2 or more persons"

Delphi3

Delphi3

 
0
 
LVL 15

Expert Comment

by:jimmack
Comment Utility
0
 
LVL 4

Author Comment

by:delphi3
Comment Utility
jimmack,

I am really impressed.
That URL and the download looks like a sherman tank and all I needed was to kill a fly.

But is there something in between? Less overkill.

Delphi3

0
 
LVL 15

Assisted Solution

by:jimmack
jimmack earned 25 total points
Comment Utility
I think you might have more success if you just do a bit of googling ;-)

I found that one by entering the following text in google:

java chat "source code" server client

It produced a lot of links (44,700).  I just picked one that looked appropriate (based on a functional system that had freely available source code).

It's difficult to know exactly what you need, so it's probably best if you check these yourself ;-)  You may also have some other words that you could include to narrow the search down.

Good luck.

Jim.
0
 
LVL 5

Expert Comment

by:lwinkenb
Comment Utility
I have modified the server a little from the link I posted earlier.  Now it can accept as many connections as you want.  Also, instead of just printing out whatever it receives, it takes the message and sends it to all the connected clients, essentially creating a chat room.

// tcpServer.java by fpont 3/2000

// usage : java tcpServer <port number>.
// default port is 1500.
// connection to be closed by client.
// this server handles only 1 connection.

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

public class tcpServer {
   
    HashSet connections;
   
    public static void main(String args[]) {
          tcpServer server = new tcpServer();
          server.begin();
    }
   
    public void begin() {
      
      int port;
      ServerSocket server_socket;
      connections = new HashSet();
      
      
      System.out.println("port = 1500 (default)");
      port = 1500;


      try {
          
          server_socket = new ServerSocket(port);
          System.out.println("Server waiting for client on port " +
                         server_socket.getLocalPort());
          
          // server infinite loop
          while(true) {
            Socket socket = server_socket.accept();
            System.out.println("New connection accepted " +
                           socket.getInetAddress() +
                           ":" + socket.getPort());
            
            Connection newConn = new Connection(socket,connections);
            newConn.start();
            synchronized(connections) {
                  connections.add(newConn);
            }
          }
          
          
      }
      
      catch (IOException e) {
          System.out.println(e);
      }
    }
}

// The following class handles each connection to the server
class Connection extends Thread {
      
      protected Socket socket;
      BufferedReader input;
      PrintWriter output;
      HashSet connections;
      
      public Connection(Socket socket, HashSet connections) {
            this.socket = socket;
            this.connections = connections;
      }
      
      public void run() {
            // print received data
            try {
                  input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                  output = new PrintWriter(socket.getOutputStream(), true);
                while(true) {
                  String message = input.readLine();
                  if (message==null) break;
                  // Iterate through all the connections, and send the message to them all
                  Iterator iterator = connections.iterator();
                  while(iterator.hasNext()) {
                        Connection conn = (Connection)iterator.next();
                        conn.sendMessage(message);
                  }
                }
            }
            catch (IOException e) {
                System.out.println(e);
            }
            
            // connection closed by client
            try {
                socket.close();
                System.out.println("Connection closed by client");
            }
            catch (IOException e) {
                System.out.println(e);
            }
            // Remove this connection from the list
            synchronized(connections) {
                  connections.remove(this);
            }
      }
      
      public void sendMessage(String message) throws IOException{
            output.println(message);
      }
}
            

            
            
0
 
LVL 5

Expert Comment

by:lwinkenb
Comment Utility
Now if you run this with the client, it wont exactly work yet.  The reason is the client only can send information to the server, it cant handle data being sent back to in.  What you will need to do is create another thread which listens for messages from the server.
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
0
 
LVL 4

Author Comment

by:delphi3
Comment Utility
Hi all,
This is a  chat business is a myth in its less than complicated, convoluted  state. A dream that some people  have while looking in a cup of coffee. There aren't  such programs and as I trail off into the 44,700 that is exactly the number who have tried to make one, finally looked at their lover and said 'give me another cup of coffee, please this one is all gone.'

Delphi3
0
 
LVL 15

Expert Comment

by:jimmack
Comment Utility
;-)
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 4

Author Comment

by:delphi3
Comment Utility
If that is all you have to offer, I will join the other 44,700 + me in sipping the coffee and needing more.

Jim, you have to be "goofy" giving that kind of advice above looking it up in google. It is indeed a waste basket of winners and loosers. Anytime I found only one entry there, that was a person asking for help and no answers were even offered. When there were mutiple respondents, maybe there was something there but another website to goto.

 lwinkenb, thanks for your response, your modification offered.
but as you note, it's not complete.

objects, your gift was something that I looked at before arriving here to pose the  Q.

To all of you bye with this bit.

Hopefully things will be more than a     " ;-) "

Delphi3






0
 
LVL 5

Expert Comment

by:lwinkenb
Comment Utility
>>lwinkenb, thanks for your response, your modification offered.
>>but as you note, it's not complete.

The server side was complete, the client needed a small modification which shouldnt have been too hard.  All you had to do was ask for it if you needed the help.

Anyways, add this class to the client:

class WaitForText extends Thread {
      
      protected Socket socket;
      protected BufferedReader socket_in;
      
      public WaitForText(Socket socket) {
            this.socket = socket;
      }
      
      public void run() {
            try {
                  socket_in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                  String socket_text;
                  while((socket_text = socket_in.readLine()) != null) {
                        System.out.println(socket_text);
                  }
            }
            catch(IOException e) {
                  System.out.println(e);
            }
      }
}

Now in the tcpClient class you need to add the following code after you connect to the server with the socket:
WaitForText wft = new WaitForText(socket);
wft.start();
0
 
LVL 4

Author Comment

by:delphi3
Comment Utility
lwinkenb,
I have worked with you gifts above.

I need to discuss the information above, are you still connected?
Specifically I cannot find reference for this?  "WaitForText" in my JB9
 You wrote:

Now in the tcpClient class you need to add the following code after you connect to the server with the socket:
WaitForText wft = new WaitForText(socket);
wft.start();
So far with this :
Two or more clients connect with the server as verfied with the notice of connections at a specific port number
But No  other information is submitted to the server  from the System.in

TIA for staying connected to this Q.
 
Delphi3
0
 
LVL 5

Expert Comment

by:lwinkenb
Comment Utility
>>Specifically I cannot find reference for this?  "WaitForText"
The WaitForText class was outlined in my last comment:

>>But No  other information is submitted to the server  from the System.in
Are you sure the message isnt being recieved by the server?
Put some debug code in the Server code after the line:
 if (message==null) break;
to see if anything is being received.



0
 
LVL 4

Author Comment

by:delphi3
Comment Utility
Hi lwinkenb,
Isn't that line in your suggestion  "if (message==null) break;"
to see if anything is being received.
written
 in:
......
class Connection extends Thread .....
....

I have to go to work in about 15 minutes and will be gone for about 5 hours.

Any further suggestions that you leave I will look at and try to use.
thanks for replying.

Delphi3
0
 
LVL 5

Expert Comment

by:lwinkenb
Comment Utility
that line is there just to make sure there isnt a read error from the socket.

My suggestion is to do this:
if (message==null) break;
System.out.println("Received from client: " + message);
0
 
LVL 4

Author Comment

by:delphi3
Comment Utility
lwinkenb,

Now, with this last addition, I can now see the line that was transmitted to the server from one or more clients.
Excellent!! I knew that something was possible because, before this last addition, I was able to
close the connections with a "."

Thanks very much.

Right now I have A linking to server and B linking to server.
The next logical jump is to make the server send some text back to the client.
Ultimately,
I really want to make changes to get this to a chat that goes between the server and 3 persons,
such as A > server linking > B  and  B > server linking >A   and C > server linking > A


I do have another program that turned up in my search for a chat program that allows a 2 person connection A > server linking > B  and  B > server linking >A  but is not compatable to make a 3rd connection because the coding is not there to keep track of who is talking to whom. It just echos from one client to and another.

Does this arrangement that we have been working on the one originally written above, do that in the form of a thread?


 But with all of these changes,  I am imposing on you, and you deserve additional points and a grade from me.

 How to accomplish this ? One option here would be to post another Q  in Java  as "points for lwinkenb". If  and when we are finished with this you can claim your points and grade from me and what is a suitable amount in exchage for addtional coding.
Your suggestion?

Or maybe you just want to quit with this Q so that I can put up another Q for you and someone else to jump in?


Delphi3
 

0
 
LVL 15

Expert Comment

by:jimmack
Comment Utility
Delphi3, the normal way that questioners seem to do this is to post a question with a title like:

"Further chat question for lwinkenb"

You might get other experts commenting, but they are aware that you are probably expecting to give the points to the expert you have named ;-)
0
 
LVL 5

Expert Comment

by:lwinkenb
Comment Utility
Right now the server is storing all of the connections in a HashSet.  This is defined as:
HashSet connections;

So connections holds a set of Connection objects.  Each of these Connection objects is basically a socket connection to a client.

Now you have a few choices on how you want the clients to talk with each other:

Choince 1:
When a client sends text to the server, the server simply sends that text to all connected clients.  This is the easiest to implement, because we dont have to worry about who we send the text to.  This is simply implemented as so:

Iterator iterator = connections.iterator();
while(iterator.hasNext()) {
  Connection conn = (Connection)iterator.next();
  conn.sendMessage(message);
}

Choice 2:
When a client sends a message to the server, we send the text to all connected client EXCEPT for the client that send the text.  This implementation is close to the same as choice 1:
Iterator iterator = connections.iterator();
while(iterator.hasNext()) {
  Connection conn = (Connection)iterator.next();
  if(!conn.equals(this))
    conn.sendMessage(message);
}

As you can see, in this implementation we make sure the connection is NOT the connection that sent the message before we call conn.sendMessage().

Choice 3:
When a client sends a message, it is supposed to only go to 1 other connected client - NOT to all of them.  To implement this, we need to distinguish between all the different Connection objects in the HashSet.  How might we do this?  Well one way is to add a username variable to the Connection class.

public String username;

Now when a client connects, you have it so the first thing it sends to you is a name.  Then you can assign that name to the username variable.  Now all your Connection objects should have a name we can call them by.

Now let's say a client called "Bill" sends a message to the server that looks like:
"John Hi, how are you doing?"
In our little made-up protocol, the first word sent is the name of the Connection object we are sending the message to.  So in this example, we will send the message "Hi, how are you doing?" to the Connection with the username of "John".  Now for the "John" Connection to know who send the message, maybe we should send the message to John like, "Bill says >> Hi, how are you doing?"

Now to send the message like this, we would do:
String messageTo = message.substring(0,message.indexOf(' ')); // get the name of the message recipient
// Now change the message so it says who it is from
message = this.username + " says >> " + message.substring(message.indexOf(' ') + 1);
while(iterator.hasNext()) {
  Connection conn = (Connection)iterator.next();
  if(conn.username.equals(messageTo)) {  // only send the message to "John"
    conn.sendMessage(message);
    break;
  }
}

This should give you a better idea of the server construction, and how to handle connected clients.  Let me know if you need me to clear up anything here.

"How to accomplish this ? One option here would be to post another Q  in Java  as "points for lwinkenb". If  and when we are finished with this you can claim your points and grade from me and what is a suitable amount in exchage for addtional coding.
Your suggestion?"

This is your choice.  Setting up a new question entitled "points for soandso" is a pretty common way to give experts additional points on experts-exchange.

0
 
LVL 4

Author Comment

by:delphi3
Comment Utility
lwinkenb,
Real solid suggestions!!!!

I have been successful in getting your choice #2, one message from one client into server then  same message out to all.  I have  added a nickname so that each  client gets who is talking attached to the line of output shared from one to all.


My next question:
 What is a reasonable step to move to the next level ???
 
#1 Modify this code  above and design a GUI using an frame and panels and textarea and textFields?

or #2
Modify another  tcp sample demo  with a GUI not designed here but implements the following.
It is single form that gives the option to be either a host or a guest. The only sick part of it is that it will only accept a host and a single guest, not multiple guests.
Considering these options that already exist:
This form has
Host IP: "localhost"
Port :"1234"
Chat Nickname: "Delphi3"
A radio button to click as if to select either Host or Guest
a button to "Connect"
a button to "Disconnect"
An image to indicate whether connected or disconnected.
A textfield to transmit a line of text to the other Nickname.
A textarea to receive all messages from everybody with a prefix of  "Delphi3 : Say it isn't so"

For #2 above, I have no idea really how to do the changes to create multiple clients.

Delphi3
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now