Simple Chat Client using Java

Hi again. I'm thring to implement a simple chat client into my game and I need some help coding it, because it's way over my head. lol thanks

Well, you have left your question very vague, and people tend to get irritated by it. First of all, you need to really specify what you need. If you have nothing and need everything....you need to start by thinking about what methods will be used to send the messages...the GUI should be the last part. Do you need a server, plan on using a public server, or in a LAN environment. If you need a server, what type? Do you plan on writing your own?
For example, if you wanted to use an IRC server as your server, you could use PircBot as your backend for the communication and then integrate that into a GUI. If you wanted AOL, there are packages out there you can use.
If you have things thought out, you need to tell us what you are really asking and what you aready have. Otherwise, you have a lot of things to think about.

Similar Messages

  • Need help coding simple chat client/server

    I'm writing a simple chat server/client... its works fine when run on console.. but when i used Frames, AWT gui's.... it seems that the thread that is used to read the incoming message is suspended ... until i press the [send] button.. It seems to me that AWT consumes the time listening to any event.... and my thread is waiting... for the some AWT specific events to occur.....
    If your interested guys.. i'm willing to post the source code.. here.

    Try using the swing components. I think they are supposed to be more thread safe than awt. There is a tutorial for dealing with threads and swing:
    http://java.sun.com/tutorial/uiswing/overview/threads.html
    hopes this helps

  • How to ping a client using java

    i got a problem, can any body help me regarding this matter. Problem is that i want to maintain a list of all the systems that are connected to server and this list is to be maintained using java, as i m building an appication in java where i need this list. Overview of the application is that i m making a PC reservation system. Database of the system will be maintained on the server and all PCs will be linked to it using RMI. For making reservation of different PCs, there must be a list of all working PCs so that selection can be made to reserve a PC. Problem is that how to maintain that list, plus continuous update this list so that if a PC stops working/breaks down, it can be removed from the list. Simple solution to this is to ping each PC after fixed time interval, but how to ping using java ??? i m usgin Microsoft Visual J++ 6.0 for developing my application, and this application will be runnig on Microsoft Windows 2000 operating system, but currently, i m in Windows 98 enviornment.

    The 1.4 API actually provides a Runtime.exec(String) but if you want to provide a String array, you can do that as well. None of the exec are static, you need to obtained a reference to the Runtime through the static method getRuntime(). So the exact call looks this way:
    Runtime  rt = Runtime.getRuntime();   // you probably want to obtain this REferance only once
    Process p = rt.exec(new String[] {"ping", target}); // yes, target is the IP or DNS name of the machine you want to ping

  • Running the client using "java"

    Hi,
    This is the error I get
    jeevak@scooby(75)%!8
    java -classpath ./dist/hello-client.jar hello.HelloClient jeevak
    Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/rpc/Stub
    I looked up jaxrpc-api.jar and it includes this class and have it in my $CLASSPATH variable.
    jeevak@scooby(76)%echo $CLASSPATH
    .:/home/g3/users/jeevak/jdom-b8/build/jdom.jar:
    /home/g3/users/jeevak/Dotstuff/xerces-1_4_4/xerces.jar:
    /home/g3/users/jeevak/Dotstuff/xerces-1_4_4/xercesSamples.jar:
    /usr/local/java/cog-0.9.13/build/cog-0.9.13/lib/cog.jar:
    /usr/local/java/cog-0.9.13/build/cog-0.9.13/lib/log4j-core.jar:
    /home/g3/users/jeevak/j2sdk1.4.1/lib/security/local_policy.jar:
    /home/g3/users/jeevak/j2sdk1.4.1/lib/security/US_export_policy.jar:
    /home/g3/users/jeevak/jwsdp-1_0_01/common/lib/jaxrpc-api.jar
    The run is successful using ant run.
    I tried to figure out the classpath ant uses but have no access to the source code for AntExecutable.java.
    Any ideas?
    -jeevak

    Try to add in your classpath all the following jar files :
    d:\jwsdp\common\lib\jaxrpc-api.jar;d:\jwsdp\common\lib\jaxrpc-ri.jar;d:\jwsdp\common\lib\activation.jar;d:\jwsdp\common\lib\mail.jar;d:\jwsdp\common\lib\jaxp-api.jar;d:\jwsdp\common\lib\saaj-api.jar;d:\jwsdp\common\lib\saaj-ri.jar;d:\jwsdp\common\endorsed\sax.jar;d:\jwsdp\common\endorsed\dom.jar;d:\jwsdp\common\endorsed\crimson.jar

  • Mpd_control - simple mpd client using dmenu

    I hacked together a simple bash script that lists artists, albums, playlists etc using dmenu.
    An example of how I usually use it:
    print a list of all artists => enter search string => choose artist => get list of albums by this artist in next screen => choose album => get list of all titles in this album => choose a title => add it to the playlist after the current song and play it.
    Actually there are a lot more options.
    I use it with a patched dmenu version from AUR (vertical- and xft-patch). But it should also work with normal dmenu.
    Have Fun!
    http://aur.archlinux.org/packages.php?ID=32179
    http://github.com/bubbl3gum/mpd_control
    #!/bin/bash
    #when set to exit, mpd_control will exit if you press escape
    #when set to break, mpd_control will go the upper level if possible
    ESC_ACTION="break"
    # source configuration file for dmenu if exists
    if [ -f $HOME/.dmenurc ]; then
    . $HOME/.dmenurc
    else
    DMENU='dmenu -i'
    fi
    addaftercurrent(){
    #playlist is empty, just add the song
    if [ "$(mpc playlist | wc -l)" == "0" ]; then
    mpc add "$1"
    #there is no current song so mpd is stopped
    #it seems to be impossible to determine the current songs' position when
    #mpd is stopped, so just add to the end
    elif [ -z "$(mpc current)" ]; then
    mpc play
    CUR_POS=$(mpc | tail -2 | head -1 | awk '{print $2}' | sed 's/#//' | awk -F/ '{print $1}')
    END_POS=$(mpc playlist | wc -l)
    mpc add "$1"
    mpc move $(($END_POS+1)) $(($CUR_POS+1))
    mpc stop
    #at least 1 song is in the playlist, determine the position of the
    #currently played song and add $1 after it
    else
    CUR_POS=$(mpc | tail -2 | head -1 | awk '{print $2}' | sed 's/#//' | awk -F/ '{print $1}')
    END_POS=$(mpc playlist | wc -l)
    mpc add "$1"
    mpc move $(($END_POS+1)) $(($CUR_POS+1))
    fi
    addaftercurrentandplay(){
    #playlist is empty, just add the song
    if [ "$(mpc playlist | wc -l)" == "0" ]; then
    mpc add "$1"
    mpc play
    #there is no current song so mpd is stopped
    #it seems to be impossible to determine the current songs' position when
    #mpd is stopped, so just add to the end
    elif [ -z "$(mpc current)" ]; then
    mpc play
    CUR_POS=$(mpc | tail -2 | head -1 | awk '{print $2}' | sed 's/#//' | awk -F/ '{print $1}')
    END_POS=$(mpc playlist | wc -l)
    mpc add "$1"
    mpc move $(($END_POS+1)) $(($CUR_POS+1))
    mpc play $(($CUR_POS+1))
    #at least 1 song is in the playlist, determine the position of the
    #currently played song and add $1 after it
    else
    CUR_POS=$(mpc | tail -2 | head -1 | awk '{print $2}' | sed 's/#//' | awk -F/ '{print $1}')
    END_POS=$(mpc playlist | wc -l)
    mpc add "$1"
    mpc move $(($END_POS+1)) $(($CUR_POS+1))
    mpc play $(($CUR_POS+1))
    fi
    case $1 in
    -a|--artist)
    while true; do
    ARTIST="$(mpc list artist | sort -f | $DMENU)";
    if [ "$ARTIST" = "" ]; then $ESC_ACTION; fi
    while true; do
    ALBUMS=$(mpc list album artist "$ARTIST" | sort -f);
    ALBUM=$(echo -e "replace all\nadd all\n--------------------------\n$ALBUMS" | $DMENU);
    if [ "$ALBUM" = "" ]; then $ESC_ACTION;
    elif [ "$ALBUM" = "replace all" ]; then
    CUR_SONG=$(mpc current)
    mpc clear
    mpc find artist "$ARTIST" | mpc add
    if [ -n "$CUR_SONG" ]; then mpc play; fi
    $ESC_ACTION
    elif [ "$ALBUM" = "add all" ]; then
    mpc find artist "$ARTIST" | mpc add
    $ESC_ACTION
    fi
    while true; do
    TITLES=$(mpc list title artist "$ARTIST" album "$ALBUM")
    TITLE=$(echo -e "replace all\nadd all\n--------------------------\n$TITLES" | $DMENU);
    if [ "$TITLE" = "" ]; then $ESC_ACTION
    elif [ "$TITLE" = "replace all" ]; then
    CUR_SONG=$(mpc current)
    mpc clear;
    mpc find artist "$ARTIST" album "$ALBUM" | mpc add
    if [ -n "$CUR_SONG" ]; then mpc play; fi
    $ESC_ACTION
    elif [ "$TITLE" = "add all" ]; then
    mpc find artist "$ARTIST" album "$ALBUM" | mpc add
    $ESC_ACTION
    fi
    while true; do
    DEC=$(echo -e "add after current and play\nadd after current\nreplace\nadd at the end" | $DMENU);
    case $DEC in
    $ESC_ACTION
    "add after current and play")
    addaftercurrentandplay "$(mpc find artist "$ARTIST" album "$ALBUM" title "$TITLE" | head -1 )"
    "add after current")
    addaftercurrent "$(mpc find artist "$ARTIST" album "$ALBUM" title "$TITLE" | head -1 )"
    "replace")
    CUR_SONG=$(mpc current)
    mpc clear
    mpc find artist "$ARTIST" album "$ALBUM" title "$TITLE" | head -1 | mpc add
    if [ -n "$CUR_SONG" ]; then mpc play; fi
    "add at the end")
    mpc find artist "$ARTIST" album "$ALBUM" title "$TITLE" | head -1 | mpc add
    esac
    $ESC_ACTION
    done
    done
    done
    done
    -t|--track)
    TITLE=$(mpc list title | sort -f | $DMENU)
    if [ "$TITLE" = "" ]; then exit; fi
    SONG=$(mpc find title "$TITLE" | head -1)
    addaftercurrentandplay "$SONG"
    -p|--playlist)
    PLAYLIST=$(mpc lsplaylists | $DMENU);
    if [ "$PLAYLIST" = "" ]; then exit; fi
    CUR_SONG=$(mpc current)
    mpc clear
    mpc load "$PLAYLIST";
    if [ -n "$CUR_SONG" ]; then mpc play; fi
    -j|--jump)
    TITLE=$(mpc playlist | $DMENU);
    if [ "$TITLE" = "" ]; then exit; fi
    POS=$(mpc playlist | grep -n "$TITLE" | awk -F: '{print $1}')
    mpc play $POS;
    -l|--longplayer)
    while true; do
    ALBUM=$(mpc list album | sort -f | $DMENU);
    if [ "$ALBUM" = "" ]; then $ESC_ACTION;
    fi
    while true; do
    TITLES=$(mpc list title album "$ALBUM")
    TITLE=$(echo -e "replace all\nadd all\n--------------------------\n$TITLES" | $DMENU);
    if [ "$TITLE" = "" ]; then $ESC_ACTION
    elif [ "$TITLE" = "replace all" ]; then
    CUR_SONG=$(mpc current)
    mpc clear;
    mpc find album "$ALBUM" | mpc add
    if [ -n "$CUR_SONG" ]; then mpc play; fi
    $ESC_ACTION
    elif [ "$TITLE" = "add all" ]; then
    mpc find album "$ALBUM" | mpc add
    $ESC_ACTION
    fi
    while true; do
    DEC=$(echo -e "add after current and play\nadd after current\nreplace\nadd at the end" | $DMENU);
    case $DEC in
    $ESC_ACTION
    "add after current and play")
    addaftercurrentandplay "$(mpc find album "$ALBUM" title "$TITLE" | head -1 )"
    "add after current")
    addaftercurrent "$(mpc find album "$ALBUM" title "$TITLE" | head -1 )"
    "replace")
    CUR_SONG=$(mpc current)
    mpc clear
    mpc find album "$ALBUM" title "$TITLE" | head -1 | mpc add
    if [ -n "$CUR_SONG" ]; then mpc play; fi
    "add at the end")
    mpc find album "$ALBUM" title "$TITLE" | head -1 | mpc add
    esac
    $ESC_ACTION
    done
    done
    done
    -h|--help)
    echo -e "-a, --artist search for artist, then album, then title"
    echo -e "-t, --track search for a single track in the whole database"
    echo -e "-p, --playlist search for a playlist load it"
    echo -e "-j, --jump jump to another song in the current playlist"
    echo -e "-l, --longplayer search for album, then title"
    echo "Usage: mpc_control [OPTION]"
    echo "Try 'mpc_control --help' for more information."
    esac
    Last edited by q0tsa (2009-11-23 10:51:43)

    Hello.
    My version of dmenu MPD client stopped to work and I founded this and it AWESOME!
    Thanks

  • Getting the log files from client using java program

    hi
    this is lalita...and i am doing a project in networking.... i am new to socket programming....i have established the socket connection between the client and server...with this site members' help....now i have to get the log files of the client system from the server.... via the created socket....i need it by tomorrow...i.e apr 12th ....as i have to show it to my guide...
    i just need a core java program that will get the log information of the client from the server......
    Can anybody please help me in this regard..... it would be of great help to me and my group....
    Anxiously awaiting for the replies....
    Thanking you and regards...
    Lalita.

    Simple.
    Server is listening on a specific port for the connection from the clients.
    Connect the client with the server on the above mentioned port.
    Open the streams on both side for the connection and run in separate thread.
    Define a protocol for communication between client and server.
    e.g after connection with the server the server send a text message to the client (send log) now the client first should the log file name and size to the sever and then send the file. the server should save the file.
    then disconnect the client or want to get another file or for other tasks define the other commands

  • Help Needed in developing simple Chatting application using flex and blazeds

    Hi,
    I followed this tutorial from adobe http://learn.adobe.com/wiki/display/Flex/Creating+a+BlazeDS+messaging+application+in+Flex+ Builder i installed tomcat server and set the path.I am unable to open server like this http://localhost:8080 but i can able to open that in this way http://127.0.0.1:8080/   .... When i create my new flex project in flash builder 4 i am getting this error
    You do not have write permission for the project output folder. Specify another location.
    can any one help me in how to get rid of this problem.I hope this forum helps me in finishing my flex project..
    Thanks
    Trinethra

    Hi,
    Need to use a scrollable resultset and depending on the need to have a stateful connection or a stateless connection you may need to query the table for every request(for stateless connection) and use the same result set for(stateful connection). and depending on the no of records in a page and the page no do some simple arithmetic and move the resultset. Hope this helps.
    rajesh

  • How to make a simple login page using java creator studio and mysql

    Hi,
    I hav got java creator studio n my sql.Can u give me the code for login page authentication and navigation

    This is a forum about Java language questions, not about how to use a developers tool. I would say to go to the site where you got java creator studio from, and look for a forum there.

  • Compiling an RMI client using Java/eclipse

    I have written a RMI Client (which connects to a server service).
    The configuration file is an XML.
    How do I compile an RMI client in ECLIPSE 3.2 using rmic?
    i havent compiled using rmic in eclipse before?
    Any ideas how to do this please?

    this could help
    http://lunar-eclipse.sourceforge.net/

  • How to read the response from the request made from teh client using java

    Hi All,
    I am using the following code to connect to the sever .
    HttpRequest httpRequest     = new HttpRequest();
    httpRequest.setMethod(method);
    if( null == uri )
    uri = "";
    httpRequest.setURI(myReplaceAll(uri, ' ',"%20"));
    httpRequest.setHeader(CONTENTTYPE, CONTENTTYPE_XML);
    httpRequest.setHeader(TRANSLATE, "f");
    httpRequest.setBody((String) null);
    IResponse httpResponse = null;
    try
    httpResponse = getRequester().perform(httpRequest);
    int httpStatus= response.getStatus();//get the response code
    I want to read the response stream that will be returned from this connection.
    Can you please help me in this case.
    Thanks and Regards,
    Anamika Mazumder.

    IResponse provides getDocument() (for XML) and getStream() (otherwise). Only one of them will work; I don't recall how it chooses. See http://help.sap.com/javadocs/NW04s/current/km/com/sapportals/wcm/util/http/HttpRequest.html#expectsResponseDocument(boolean).
    And, btw, do not construct URIs by text replacement; there are proper URI parsing/generator classes for this purpose in KM.

  • Simple integer generation  using java math classes

    I want to generate a integer which should be combination of 2 integer and one int
    and anytime I call generate it should generate same value for same input and for different combinations it should generate different value.
    for example I passed to the service two integers 24, 25 and one int 76
    assume it generated 242576
    I restart jvm to the service pass the same values mentioned above it should return me same output 242576.
    I want to do this using some math functionality not using string concatinating ?Any suggestions on acheiving this? any help is greatly appreciated.
    miro

    How would you arrive at 242576 from 24, 25 and 76 when performing the operation by hand, on paper? What calculations would you need to perform?
    Your other requirements are standard properties of programming: unless you go out of your way to make it otherwise, methods/functions tend to produce the same output based on the same input.
    BTW, you won't need any math classes for this, just mathematical operators like +, -, *, / etc.

  • Java chat client behind the proxy or fire wall

    i am developing the chat application useing java.net.*.but i am not able to get connectivity behind the firewall or proxy on the java client.pls help me out

    to guarantee easy to use, no problem chat applet then you will need to have the chat server running on port 80 and the client use http request/response system
    first problem is that the applet will have to have been delivered from port 80 on the same ip# so you will either have to use Servlets or write your own web server with chat facilities
    you will need to maitain persistent/ pseudo persistent http connections for the server to deliver messages to clients, you can assume that a connection will remain open for ~ 5 minutes after a request from the client
    use HTTP/1.1 for reliable Connection: keep-alive and request/response pipelining
    with all that in place your client method is...
    register and send GET /chat <wait for upto 5 mins>
    if there is client activity send POST/chat <wait for upto 5 mins>
    if the above waits timeout send GET/chat <wait for upto 5mins>
    server method...
    accept GET/POST requests from client
    if there is chat to deliver, reply to most recent request from client
    if you recive another request before the previous one's reply is used, send a No Content reply to the previous request

  • Socket example using Java 5

    Last year I posted 4 programs that provided a simple client server using both stream sockets and NIO. I decided as an exercise in using Java 5 to port that code and try to use as many of the new features as possible. The following code is very long and does what all the previous example programs did. In replies do not repost the whole of this message.
    It provides a simple chat like client and server. The user can request either a stream connection or a NIO connection or provide one of their own.
    //========================== MsgSwitch.java ===========================//
    package pkwnet.msgswitch;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    import java.util.logging.Handler;
    * main class for message switch
    * command line arguments are
    * -p port number for server
    * -s run server
    * -a server ip address including port for client
    * -i idle timer in seconds
    * -n use NIO
    * -c specify connection class
    public class MsgSwitch {
        static private int errors = 0;
        static private String address = "127.0.0.1:6060";
        static private String connectionClass = "pkwnet.msgswitch.StreamConnection";
        static public void main(String [] args) {
            int port = 6060;
            int idleTime = 600;
            boolean server = false;
            boolean nio = false;
            Logger logger = Logger.getLogger("msgswitch");
            for(String arg : args) {
                if(arg.startsWith("-a")) {
                    address = arg.substring(2);
                } else if(arg.startsWith("-p")) {
                    port = argToInt(arg);
                    server = true;
                } else if(arg.startsWith("-i")) {
                    idleTime = argToInt(arg);
                } else if (arg.startsWith("-s")) {
                    server = true;
                } else if (arg.startsWith("-c")) {
                    connectionClass = arg.substring(2);
                } else if (arg.startsWith("-n")) {
                    connectionClass = "pkwnet.msgswitch.NIOConnection";
                } else {
                    String err = "unknown argument=" + arg;
                    logger.severe(err);
                    System.err.println(err);
                    errors++;
            if (errors == 0) {
                if (server) {
                    new Server().listen(port,idleTime, nio);
                } else {
                    new Client().start(address, nio);
            } else {
                fail(errors + " errors encountered", null);
        static private int argToInt(String arg) {
            int val = 0;
            try {
                val = Integer.parseInt(arg.substring(2));
            } catch (NumberFormatException e) {
                String err = "invalid argument format: " + arg;
                Logger.getLogger("msgswitch").severe(err);
                System.err.println(err);
                errors++;
            return val;
        static public void fail(String err, Throwable e) {
            String msg = "Operation terminated: " + err;
            Logger.getLogger("msgswitch").log(Level.SEVERE, msg, e);
            System.err.println(msg);
            System.exit(12);
        static public Connection getConnection() {
            Connection conn = null;
            try {
                conn = (Connection) Class.forName(connectionClass).newInstance();
            } catch (Exception e) {
                fail ("connection class error", e);
            return conn;
        static public void logCaller(Logger logger, Level level) {
            String text = "CALLED";
            if (logger.isLoggable(level)) {
                try {
                    throw new Exception("logging stack");
                } catch (Exception e) {
                    StackTraceElement [] st = e.getStackTrace();
                    if (st.length > 1) {
                        text += formatElement(st[1]);
                    if (st.length >2) {
                        text += formatElement(st[2]);
                logger.log(level, text);
        static private String formatElement(StackTraceElement ste) {
            return "\n    " + ste.getClassName() + "." + ste.getMethodName()
                + "(" + ste.getFileName() + ":" + ste.getLineNumber() + ")";
    //================= Client.java =============================================//
    package pkwnet.msgswitch;
    * a simple Swing chat GUI using Java 5 and sockets.
    * @author PKWooster
    * @version 1.0 August 31,2005
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JDialog;
    import javax.swing.SwingUtilities;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.BorderLayout;
    import static java.awt.BorderLayout.*;
    client GUI class
    public class Client extends JFrame implements ConnectionListener {
         // swing GUI components
         private JTextField userText = new JTextField(40);
         private JTextArea sessionLog = new JTextArea(24,40);
         private JTextField statusText = new JTextField(40);
         private JPanel outPanel = new JPanel();
         private JScrollPane sessionLogScroll = new JScrollPane(sessionLog);
         private JMenuBar menuBar = new JMenuBar();
         private JMenuItem startItem = new JMenuItem("Start");
         private JMenuItem hostItem = new JMenuItem("Host");
         private JMenuItem aboutItem = new JMenuItem("About");
         private JMenuItem abortItem = new JMenuItem("Abort");
         private JMenuItem exitItem = new JMenuItem("Exit");
         private JMenu fileMenu = new JMenu("File");
         private JMenu helpMenu = new JMenu("Help");
         private Container cp;
         private String address;
        private Connection connection;
        private boolean sendReady = false;
        private boolean nio = false;
         Client() {
        public void start(String address, boolean nio) {
            this.address = address;
            this.nio = nio;
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    runClient();
        private void runClient() {   
            connection = MsgSwitch.getConnection();
            connection.addConnectionListener(this);
              buildMenu();
              cp = getContentPane();
              sessionLog.setEditable(false);
              outPanel.add(new JLabel("Send: "));
              outPanel.add(userText);
              // enter on userText causes transmit
              userText.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){userTyped(evt);}
              cp.setLayout(new BorderLayout());
              cp.add(outPanel,NORTH);
              cp.add(sessionLogScroll,CENTER);
              cp.add(statusText,SOUTH);
              setStatus("Closed");
              addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    mnuExit();
              pack();
            setVisible(true);
    * attempt to send the contents of the user text field
        private void userTyped(ActionEvent evt) {
            if (sendReady) {
                String txt = evt.getActionCommand()+"\n";
                userText.setText("");
                toSessionLog("> ", txt);
                sendReady = false;
                connection.send(txt);
    * append text to the session log
         private void toSessionLog(String prefix, String txt) {
              sessionLog.append(prefix + txt);
              sessionLog.setCaretPosition(sessionLog.getDocument().getLength() ); // force last line visible
    * build the standard menu bar
         private void buildMenu()
              JMenuItem item;
              // file menu
              startItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuStart();}});
              fileMenu.add(startItem);
              hostItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuHost();}});
              fileMenu.add(hostItem);
              exitItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuExit();}});
              fileMenu.add(exitItem);
              menuBar.add(fileMenu);
              helpMenu.add(aboutItem);
              aboutItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuAbout();}});
              menuBar.add(helpMenu);
              setJMenuBar(menuBar);
    * start and stop communications from start menu
         private void mnuStart() {
            if(connection.getState() ==  Connection.State.CLOSED) {
                connection.connect(address);
            } else {
                connection.disconnect();
    *  prompt user for host in form address:port
        private void mnuHost() {
              String txt = JOptionPane.showInputDialog("Enter host address:port", connection.getAddress());
              if (txt == null)return;
            address = txt;
         private void mnuAbout() {
              JDialog dialog = new JDialog(this, "About Client");
              JTextField text = new JTextField("Simple character client");
            dialog.getContentPane().add(text);
            dialog.pack();
            dialog.setVisible(true);
         // exit menu
         private void mnuExit() {
            exit();
        private void exit() {
              connection.disconnect();
              System.exit(0);
         private void setStatus(String st) {
            statusText.setText(st);
         private void setStatus(Connection.State state) {
            switch(state) {
                case OPENED:
                    startItem.setText("Stop");
                    setStatus("Connected to "+address);
                    break;
                case CLOSED:
                    startItem.setText("Start");
                    setStatus("Disconnected");
                    break;
                case OPENING:
                    setStatus("Connecting to "+address);
                    startItem.setText("Abort");
                    break;
                case CLOSING:
                    setStatus("Disconnecting from "+address);
                    startItem.setText("Abort");
                    break;
        public void stateChanged(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
        public void dataAvailable(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
                    String txt = event.getData();
                    if (txt == null) {
                        txt = "$null$";
                    toSessionLog("< ", txt + "\n");   
        public void sendAllowed(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
                    sendReady = true;
        public void accept(ConnectionEvent event) {
    //========================== Server.java ===============================//
    package pkwnet.msgswitch;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    * a simple message switch using stream based socket i/o
    * a very simple text message switching program
    * user commands start with $ and consist of blank seperated arguments
    * other lines sent by the user are forwarded
    * $on nickname targets
    *    sign on as nickname, sending to targets
    * $to targets
    *    change target list, reports current value
    * $list nicknames
    *    list status of specified nicknames
    * $list
    *    list all connected users
    * $off
    *    sign off
    * @author PKWooster
    * @version 1.0 September 1, 2005
    public class Server {
        private ConcurrentHashMap<String, User> perUser = new ConcurrentHashMap<String,User>();
        private Timer idleTimer;
        private Connection conn;
        public void listen(int port, final int idleTime, boolean nio) {
            idleTimer = new Timer();
            idleTimer.scheduleAtFixedRate(new TimerTask(){public void run(){oneSec();}},0,1000);
            conn = MsgSwitch.getConnection();
            conn.addConnectionListener(new ConnectionListener() {
                public void stateChanged(ConnectionEvent event) {
                public void dataAvailable(ConnectionEvent event) {
                public void sendAllowed(ConnectionEvent event) {
                public void accept(ConnectionEvent event) {
                    Connection uconn = event.getConnection();
                    new User(uconn, perUser, idleTime);
            conn.listen(port);
            idleTimer.cancel();
        private void oneSec() {
            Collection<User> uc = perUser.values();
            for(User u : uc) {
                u.oneSec();
    //================= User.java  ==============================================//
    package pkwnet.msgswitch;
    import java.io.*;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.atomic.AtomicInteger;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    * defines the processing for a message switch user
    * @author PKWooster
    * @version 1.0 June 15,2004
    public class User implements ConnectionListener {
        private ConcurrentHashMap<String, User> perUser;
        private String name;
        private String address;
        private boolean signedOn = false;
        private String[] targets;
        private AtomicInteger remainingTime;
        private int idleTime;
        Connection conn;
        Logger logger;
      * construct a user, link it to its connection and put it in the perUser table
        User(Connection conn, ConcurrentHashMap<String,User>p, int idle) {
            this.conn = conn;
            logger = Logger.getLogger("msgswitch.user");
            conn.addConnectionListener(this);
            address = conn.getAddress();
            logger.info("creating user " + address);
            perUser = p;
            idleTime = idle;
            remainingTime = new AtomicInteger(idleTime);
            rename(address);
            targets = new String[0];
    * process state changes
        public void stateChanged(ConnectionEvent event) {
            if(event.getState() == Connection.State.CLOSED) {
                close(false);
    * data is available, process commands and forward other data.
        public void dataAvailable(ConnectionEvent event) {
            String msg = event.getData();
            if (msg.startsWith("$")) {
                doCommand(msg);
            } else {
                forward(msg);
            remainingTime.set(idleTime);
    * do nothing for sendAllowed events
        public void sendAllowed(ConnectionEvent event) {
    * do nothing for accept events
        public void accept(ConnectionEvent event) {
    * called once per second by the server main thread.
        public void oneSec() {
            if(idleTime != 0 && 1 > remainingTime.decrementAndGet()) {
                close(true);
    * send a message
        private void send(String msg) {
            conn.send(msg);
            remainingTime.set(idleTime);
    * forward data messages to other users
    * @param txt the message to send
        private void forward(String txt) {
            txt = name+": "+txt + "\n";
            if(0 < targets.length) {
                for(String target :targets) {
                    User user = perUser.get(target);
                    if(user != null) {
                        user.send(txt);
            } else {
                for (User user : perUser.values()) {
                    if (user != this) {
                        user.send(txt);
    * execute command messages, commands start with a $
    * and contain arguments delimited by white space.
    * @param command the command string
        private void doCommand(String command) {
            boolean good = false;
            command = command.substring(1).trim();
            if(command.length() > 0) {
                String [] args = command.split("\\s+");
                if(args[0].equals("on")) {
                    good = signOn(args);
                } else if(args[0].equals("off")) {
                    good = signOff(args);
                } else if(args[0].equals("list")) {
                    good = listUsers(args);
                } else if(args[0].equals("to")) {
                    good = setTargets(args,1);
                } else if(args[0].equals("idle")) {
                    good = setIdle(args);
                if(!good) {
                    send("invalid command=" + command + "\n");
    * sign on command
        private boolean signOn(String [] args) {
            boolean good = false;
            if(args.length >1) {
                String nm = args[1];
                logger.info("signing on as: " + nm);
                if(rename(nm)) {
                    conn.setName(name);
                    send("Signed on as " + name + "\n");
                    signedOn = true;
                    good = true;
                    setTargets(args,2);
                } else {
                    send("name="+nm+" already signed on\n");
            return good;
    * set forwarding targets
        private boolean setTargets(String [] args, int start) {
            if(start < args.length) {
                targets = new String[args.length-start];
                System.arraycopy(args, start, targets, 0, targets.length);
            String str = "to=";
            for(String target : targets) {
                str += (target + " ");
            send(str+"\n");
            return true;
    * set idle timeout
        private boolean setIdle(String[] args) {
            try {
                idleTime = new Integer(args[1]).intValue();
                remainingTime.set(idleTime);
                send("idle time set to "+idleTime+"\r\n");
                return true;
            } catch(NumberFormatException exc) {
                return false;
    * sign off
        private boolean signOff(String [] args) {
            close(true);
            return true;
    * list connected users
        private boolean listUsers(String [] args) {
            TreeSet<String> allUsers = new TreeSet<String>(perUser.keySet());
            HashSet<String> t = new HashSet<String>(Arrays.asList(targets));
            LinkedList<String> users;
            String response = "On,Target,Nickname\n";
            if(args.length < 2) {
                users = new LinkedList<String>(allUsers);
            } else {
                users = new LinkedList<String>();
                for (int i = 1; i < args.length; i++) {
                    users.add(args);
    for(String username : users) {
    if(username.equals(name)) {
    response += "*,";
    } else {
    response += (allUsers.contains(username) ? "y," : "n,");
    response += (t.contains(username) ? "y," : "n,");
    response += (username + "\n");
    send(response);
    return true;
    * rename this user, first we attempt to add the new name then we remove
    * the old one. Both names will be registered for a short while.
    * @param newname the new name for this user
    * @return true if the rename was successful
    private boolean rename(String newname) {
    boolean b = false;
    logger.info("rename name="+name+" newname="+newname);
    if (name != null && name.equals(newname)) {
    b = true;
    } else if (null == perUser.putIfAbsent(newname, this)) {
    if (name != null) {
    perUser.remove(name);
    name = newname;
    b = true;
    return b;
    * delete from perUser and close our connection
    private void close(boolean disconnect) {
    logger.info("closing user "+name);
    perUser.remove(name);
    if (disconnect) {
    conn.disconnect();
    //====================== Connection.java ===============================//
    package pkwnet.msgswitch;
    import java.util.HashSet;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    public abstract class Connection {
    public enum State {CLOSED, OPENING, OPENED, CLOSING}
    private HashSet<ConnectionListener> listeners = new HashSet<ConnectionListener>();
    private State state = State.CLOSED;
    private String host = "127.0.0.1";
    private int port = 6060;
    private String name = "unconnected";
    public Connection() {
    public abstract void listen(int port);
    public abstract void connect(String address);
    public abstract void disconnect();
    public abstract void send(String message);
    public void addConnectionListener(ConnectionListener listener) {
    listeners.add(listener);
    public void removeConnectionListener(ConnectionListener listener) {
    listeners.remove(listener);
    protected void fireDataAvailable(String data) {
    for (ConnectionListener listener : listeners) {
    listener.dataAvailable(new ConnectionEvent(this, state, data));
    private void fireStateChanged() {
    for (ConnectionListener listener : listeners) {
    listener.stateChanged(new ConnectionEvent(this, state));
    protected void fireSendAllowed() {
    for (ConnectionListener listener : listeners) {
    listener.sendAllowed(new ConnectionEvent(this, state));
    protected void fireAccept(Connection conn) {
    for (ConnectionListener listener : listeners) {
    listener.accept(new ConnectionEvent(this, conn));
    protected void setState(State state) {
    if (this.state != state) {
    this.state = state;
    fireStateChanged();
    public State getState() {
    return state;
    protected void setAddress(String address) {
              int n = address.indexOf(':');
              String pt = null;
    setName(address);
    if(n == 0) {
                   host = "127.0.0.1";
                   pt = address.substring(1);
              else if(n < 0) {
                   host = address;
                   port = 5050;
              } else {
    host = address.substring(0,n);
                   pt = address.substring(n+1);
    if (pt != null) {
    try {
    port = Integer.parseInt(pt);
    } catch (NumberFormatException e) {
    port = -1;
    public String getName() {
    return name;
    public void setName(String value) {
    name = value;
    public String getAddress() {
    return host + ":" + port;
    public String getHost() {
    return host;
    public void setPort(int value) {
    port = value;
    public int getPort() {
    return port;
    //=================== ConnectionEvent.java ================================//
    package pkwnet.msgswitch;
    public class ConnectionEvent extends java.util.EventObject {
    private final String data;
    private final Connection.State state;
    private final Connection conn;
    public ConnectionEvent(Object source, Connection.State state, String data, Connection conn) {
    super(source);
    this.state = state;
    this.data = data;
    this.conn = conn;
    public ConnectionEvent(Object source, Connection.State state, String data) {
    this(source, state, data, null);
    public ConnectionEvent(Object source, Connection.State state) {
    this(source, state, null, null);
    public ConnectionEvent(Object source, Connection conn) {
    this(source, conn.getState(), null, conn);
    public Connection.State getState() {
    return state;
    public String getData() {
    return data;
    public Connection getConnection() {
    return conn;
    //============================ ConnectionListener.java ===================//
    package pkwnet.msgswitch;
    public interface ConnectionListener extends java.util.EventListener {
    public void stateChanged(ConnectionEvent event);
    public void dataAvailable(ConnectionEvent event);
    public void sendAllowed(ConnectionEvent event);
    public void accept(ConnectionEvent event);
    //============================ StreamConnection.java ===================//
    package pkwnet.msgswitch;
    import java.net.Socket;
    import java.net.ServerSocket;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.IOException;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    * provides stream socket i/o of character strings
    * @author PKWooster
    * @version 1.0 September 1, 2005
    public class StreamConnection extends Connection {
    private Socket sock;
    private BufferedReader in;
    private BufferedWriter out;
    private Thread recvThread = null;
    private Thread sendThread = null;
    protected LinkedBlockingQueue<String> sendQ;
    Logger logger;
    public StreamConnection() {
    super();
    logger = Logger.getLogger("msgswitch.stream");
    sendQ = new LinkedBlockingQueue<String>();
    * open a socket and start i/o threads
    public void connect(String ipAddress) {
    setAddress(ipAddress);
    try {
    sock = new Socket(getHost(), getPort());
    connect(sock);
    } catch (IOException e) {
    logger.log(Level.SEVERE, "Connection failed to=" + ipAddress, e);
    private void connect(Socket sock) {
    this.sock = sock;
    String ipAddress = getAddress();
    try {
    in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
    recvThread = new Thread(new Runnable() {
    public void run() {
    doRecv();
    },"Recv." + getName());
    sendThread = new Thread(new Runnable() {
    public void run() {
    doSend();
    },"Send."+getName());
    sendThread.start();
    recvThread.start();
    setState(State.OPENED);
    } catch(IOException e) {
    logger.log(Level.SEVERE, "Connection failed to="+ipAddress, e);
    public void listen(int port) {       
    StreamConnection sconn;
    setPort(port);
    try {
    ServerSocket ss = new ServerSocket(port);
    while(true) {
    Socket us = ss.accept();
    sconn = new StreamConnection();
    String ipAddress = us.getInetAddress() + ":" + us.getPort();
    sconn.setAddress(ipAddress);
    sconn.connect(us);
    fireAccept(sconn);
    } catch(Exception e) {
    logger.log(Level.SEVERE, "listen failed", e);
    * close the socket connection
    public void disconnect() {
    logger.fine("disconnect sock=" + sock + " state="+ getState());
    if(getState() == State.OPENED) {
    setState(State.CLOSING);
    try {
    sock.shutdownOutput();
    } catch(IOException ie) {
    logger.log(Level.SEVERE, "showdown failed", ie);
    } else if(getState() != State.CLOSED) {
    try {
    sock.close();
    } catch(Exception e) {
    logger.log(Level.SEVERE, "close failed", e);
    if (sendThread.isAlive()) {
    sendThread.interrupt();
    sendQ.clear();
    setState(State.CLOSED);
    public void send(String message) {
    if (getState() == State.OPENED) {
    try {
    sendQ.put(message);
    } catch(InterruptedException e) {
    logger.log(Level.SEVERE, "sendQ put interrupted", e);
    setState(State.CLOSING);
    disconnect();
    * sets the public name of this connection
    public void setName(String name) {
    super.setName(name);
    if (sendThread != null) {
    try {
    recvThread.setName("recv." + name);
    sendThread.setName("send." + name);
    } catch(Exception e) {
    logger.log(Level.SEVERE, "nameing threads failed", e);
    * the main loop for the send thread
    private void doSend() {
    String msg;
    boolean running = true;
    while (running) {
    if (sendQ.size() == 0) {
    fireSendAllowed();
    try {
    msg = sendQ.take();
    out.write(msg);
    out.flush();
    } catch(Exception e) {
    if (getState() == State.OPENED) {
    logger.log(Level.SEVERE, "write failed", e);
    setState(State.CLOSING);
    disconnect();
    running = false;
    * the main loop for the receive thread
    private void doRecv() {
    String inbuf;
    while (getState() == State.OPENED) {
    try {
    inbuf = in.readLine();
    } catch(Exception e) {
    if (getState() == State.OPENED) {
    logger.log(Level.SEVERE, "readline failed", e);
    inbuf = null;
    if(inbuf == null) {
    logger.fine("null received on: " + getAdd

    Here are three of them:
    NIO server
    NIO client
    Multithreaded server
    The stream based client example seems to have been deleted, probably lost in the troll wars. I also posted a new Simple multithreaded server that uses the same protocol. As the client is missing, I'll repost it.

  • Need Help with Simple Chat Program

    Hello Guys,
    I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class Client
    extends JPanel {
    public static void main(String[] args) throws IOException {
    String name = args[0];
    String host = args[1];
    int port = Integer.parseInt(args[2]);
    final Socket s = new Socket(host, port);
    final Client c = new Client(name, s);
    JFrame f = new JFrame("Client : " + name);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    c.shutDown();
    System.exit(0);
    f.setSize(300, 300);
    f.setLocation(100, 100);
    f.setContentPane(c);
    f.setVisible(true);
    private String mName;
    private JTextArea mOutputArea;
    private JTextField mInputField;
    private PrintWriter mOut;
    public Client(final String name, Socket s)
    throws IOException {
    mName = name;
    createUI();
    wireNetwork(s);
    wireEvents();
    public void shutDown() {
    mOut.println("");
    mOut.close();
    protected void createUI() {
    setLayout(new BorderLayout());
    mOutputArea = new JTextArea();
    mOutputArea.setLineWrap(true);
    mOutputArea.setEditable(false);
    add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
    mInputField = new JTextField(20);
    JPanel controls = new JPanel();
    controls.add(mInputField);
    add(controls, BorderLayout.SOUTH);
    mInputField.requestFocus();
    protected void wireNetwork(Socket s) throws IOException {
    mOut = new PrintWriter(s.getOutputStream(), true);
    final String eol = System.getProperty("line.separator");
    new Listener(s.getInputStream()) {
    public void processLine(String line) {
    mOutputArea.append(line + eol);
    mOutputArea.setCaretPosition(
    mOutputArea.getDocument().getLength());
    protected void wireEvents() {
    mInputField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String line = mInputField.getText();
    if (line.length() == 0) return;
    mOut.println(mName + " : " + line);
    mInputField.setText("");

    Thanks for ur help!i have moved BufferedReader outside the loop. I dont think i am getting exception as i can c the output once.What i am trying to do is repeat the process which i m getting once.What my method does is first one sends the packet to multicasting group (UDP) and other method receives the packets and prints.

  • Chat client Help

    I am writing a chat client in java and I was wondering how to change the color of the text for each person. What I mean is is it possible to have the text from one user display red and the text from another user display blue. Any help would be nice.

    Is there a way to format text with html using JEditorPane and/or JTextPane; Read the API. You will find links to the tutorials.

Maybe you are looking for