Java Chat, server/client*x

Hey,
I'm trying to make a chat and I've made the server and client, and the server can accept several clients. Only; they communicate client-server, and not client-server-client (if you get what I mean) like I want them to, pretty obviously, since its a chat. I'm still very new to this, heres my code anyhow:
Server
import java.net.*;
import java.io.*;
public class OJChatServer{
     public static void main(String[] args) throws IOException{
          int port=2556;
          boolean listening = true;
          ServerSocket cServerSocket = null;
          try{
               cServerSocket = new ServerSocket(port);
               System.out.println("Server started; Waiting for client(s) to connect.");
          } catch(IOException e){
               System.err.println("Could not listen on port: "+port);
               System.exit(1);
          while(listening){
               try{
                    new handleClient(cServerSocket.accept()).start();
               } catch(IOException e){
                    System.err.println("Accept has failed");
                    System.exit(1);
          cServerSocket.close();
     static class handleClient extends Thread{
          private Socket clientSocket = null;
          private PrintWriter send;
          private BufferedReader recieve;
          private String inputString, outputString;
          private String clientName = "";
          public handleClient(Socket acceptedSocket){
               //super("handleClient");
               this.clientSocket = acceptedSocket;
          public void run(){
               try{
                    recieve = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                    send = new PrintWriter(clientSocket.getOutputStream(), true);
                    inputString = recieve.readLine();
                    clientName = inputString;
                    System.out.println("Client \""+clientName+"\" has connected. ("+clientSocket+")");
                    while(inputString != null){
                         outputString = processInput(inputString);
                    //     outputString = send.readLine();
                         send.println(outputString);
                         if(inputString.equalsIgnoreCase("Quit")||inputString.equalsIgnoreCase("/Quit")) break;
                         inputString = recieve.readLine();
                    System.out.println("Client \""+clientName+"\" has disconnected. ("+clientSocket+")");
               send.close();
               recieve.close();
               clientSocket.close();
               } catch(IOException e){
                    //e.printStackTrace();
                    System.out.println("Client \""+clientName+"\" has disconnected. ("+clientSocket+")");
          }//run()
          static String processInput(String theInput){
               String theOutput = "From server. Test";
               return theOutput;
     }//handleClient
}//OJChatServer---------------------------------------------------------------------------------------------
Client
import java.net.*;
import java.io.*;
public class OJChatClient{
     public static void main(String[] args) throws IOException{
          String nickname = "Guest";
          String host = "localhost";
          int port = 2556;
          Socket cClientSocket = null;
          PrintWriter send = null;
          BufferedReader recieve = null;
          BufferedReader stdIn = null;
          String fromServer, fromUser;
          System.out.println("Welcome to Ove's Java Chat!\nFor help and commands type: /help");
          nickname = KeyboardReader.readString("Enter nickname: ");
          System.out.println("Connecting to host...");
          try{
               cClientSocket = new Socket(host, port);
               send = new PrintWriter(cClientSocket.getOutputStream(), true);
               System.out.println("Connection established.");
          } catch(UnknownHostException e){
               System.err.println("Unknown host: "+host);
               System.exit(1);
          } catch(IOException e){
               System.err.println("Couldn't get I/O for connection: "+host+"\nRequested host may not exist or server is not started");
               System.exit(1);
          send.println(nickname);
          stdIn = new BufferedReader(new InputStreamReader(System.in));
          recieve = new BufferedReader(new InputStreamReader(cClientSocket.getInputStream()));
          while((fromServer = recieve.readLine())!=null){
               System.out.println("Server: "+fromServer);
               fromUser = stdIn.readLine();
               if(fromUser!=null){
                    //System.out.println(nickname+": "+fromUser);
                    send.println(fromUser);
               if(fromUser.equalsIgnoreCase("Quit")||fromUser.equalsIgnoreCase("/Quit")) break;
          System.out.println("Closing connection...");
          send.close();
          recieve.close();
          stdIn.close();
          cClientSocket.close();
          System.out.println("Connection terminated.");
          System.out.println("Goodbye and happy christmas!");
}I want to make it graphical too, but I want to make it work like it should, before i tackle trying Swing out. This code isn't completely complete yet, as you can see. It doesn't handle the clients messages correctly yet.
What I want to know is how i should send a message from a client to all the other Sockets on the server.

It compiles, but it gives an error when the client connects.
import java.net.*;
import java.io.*;
public class OJChatServer4{
     static Socket[] clientSockets = new Socket[100];
     static int socketCounter = 0;
     public static void main(String[] args) throws IOException{
          int port=2556;
          boolean listening = true;
          ServerSocket cServerSocket = null;
          try{
               cServerSocket = new ServerSocket(port);
               System.out.println("Server started; Waiting for client(s) to connect.");
          } catch(IOException e){
               System.err.println("Could not listen on port: "+port);
               System.exit(1);
          while(listening){
               try{
                    clientSockets[socketCounter] = cServerSocket.accept();
                    new handleClient(clientSockets[socketCounter]).start();
                    socketCounter++;
               } catch(IOException e){
                    System.err.println("Accept has failed");
                    System.exit(1);
          cServerSocket.close();
     static class handleClient extends Thread{
          private Socket clientSocket = null;
          public static PrintWriter send;
          private BufferedReader recieve;
          private String inputString, outputString;
          private String clientName = "";
          public handleClient(Socket acceptedSocket){
               //super("handleClient");
               this.clientSocket = acceptedSocket;
          public void run(){
               try{
                    recieve = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                    send = new PrintWriter(clientSocket.getOutputStream(), true);
                    inputString = recieve.readLine();
                    clientName = inputString;
                    System.out.println("Client \""+clientName+"\" has connected. ("+clientSocket+")");
                    while(inputString != null){
                         //outputString =
                         processInput(inputString);
                    //     outputString = send.readLine();
                         send.println(outputString);
                         if(inputString.equalsIgnoreCase("Quit")||inputString.equalsIgnoreCase("/Quit")) break;
                         inputString = recieve.readLine();
                    System.out.println("Client \""+clientName+"\" has disconnected. ("+clientSocket+")");
               send.close();
               recieve.close();
               clientSocket.close();
               } catch(IOException e){
                    //e.printStackTrace();
                    System.out.println("Client \""+clientName+"\" has disconnected. ("+clientSocket+")");
          }//run()
          static void processInput(String theInput) throws IOException{
               //String theOutput = "Test From server.";
               PrintWriter sendToAll;
               sendToAll = new PrintWriter(clientSockets[socketCounter].getOutputStream(), true);
               for(int i=0;i<socketCounter;i++){
                    sendToAll.println(theInput);
               //return theOutput;
     }//handleClient
}//OJChatServer

Similar Messages

  • Java Chat (Server, Client Socket Connection)

    Assignment:
    The assignment is to deliver two source codes that can run a Server (1) and Clients (2) in order to create a simpel chat program. The server has to wait and check an IP (localhost) + Port, and the client has to connect to that port and create a socket connection. The only thing that should be done is create a new socket connection for each client... and when a client sends a message, the message should be delivered to all clients connected to the server.
    Problem...
    However I can read an edit Java, it's difficult for me to write it. I allready found many turturials about socket connections on the internet, and tried to edit those, but they don't really do what I want unless I really write new shit. Is there a way you guys can help me with this, or that you find a really good website that fits my question?

    According to me ,
    take string variable 'str'
    Take some class ,I think u already taken.....
    Scoket scoket = new Socket(IP,port);
    OutputStream out;
    IInputStream in;
    in = socket.getInputStream();
    out = socket.getOutputStream();
    If sends the msg then use
    out.writeObject(str);
    This line sends data to the other user
    msg resivce from client then use
    str = in.readInput();
    & this str set to the any objects out put .
    Such as TextField.setText(str);
    //Server.class
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class Server extends JFrame
              private JTextField enterdField;
              private JTextArea displayArea;
              private ObjectOutputStream output;
              private ObjectInputStream input;
              private ServerSocket server;
              private Socket connection;
              private int counter=1;
              public Server()
                        super("Server");
                        enterdField = new JTextField();
                        enterdField.setEditable(false);
                        enterdField.addActionListener(
                             new ActionListener()
                                       public void actionPerformed(ActionEvent event)
                                                 sendData(event.getActionCommand());
                                                 //System.out.println(event.getActionCommand());
                                                 enterdField.setText("");
                   add(enterdField,BorderLayout.NORTH);
                   displayArea = new JTextArea();
                   add(new JScrollPane(displayArea),BorderLayout.CENTER);
                   setSize(300,150);
                   setVisible(true);
              public void runServer()
                        try
                                  server = new ServerSocket(12345,100);
                                  while(true)
                                            try
                                                      waitForConnection();
                                                      getStreams();
                                                      processConnection();
                                            catch(EOFException eofexception)
                                                      displayMessage("\nServer terminated connection");
                                            finally
                                                      closeConnection();
                                                      counter++;
                        catch(IOException ioException)
                                  ioException.printStackTrace();
              private void waitForConnection() throws IOException
                        displayMessage("Waiting for connection");
                        connection = server.accept();
                        //System.out.println(server.accept());
                        System.out.println(connection.getInetAddress());//Server Address and Hostname.
                        displayMessage("Connection"+counter +"received from :"+connection.getInetAddress().getHostName());
              private void getStreams() throws IOException
                        System.out.println("Start getStream");
                        output = new ObjectOutputStream(connection.getOutputStream());
                        output.flush();
                        input = new ObjectInputStream(connection.getInputStream());
                        displayMessage("\nGot I/O stream\n");
              private void processConnection() throws IOException //Read data from Client for Server.
                        String message="Connection sucessful To Client";
                        sendData(message);
                        int i=0;
                        setTextFieldEditable(true);
                        do
                                  try
                                            message =(String) input.readObject();//For Client
                                            System.out.println("Input from :"+message);//From Client
                                            displayMessage("\n" + message);
                                            System.out.println("\n" + i++);
                                  catch(ClassNotFoundException classnotfoundexception)
                                            displayMessage("\nUnknown object type recived");
                        while(!message.equals("CLIENT>>>TERMINATE"));
              private void closeConnection()
                        displayMessage("\nTeminating connection");
                        setTextFieldEditable(false);
                        try
                                  output.close();
                                  input.close();
                                  connection.close();
                        catch(IOException ioException)
                                  ioException.printStackTrace();
              private void sendData(String message)//Write data to the Client from the Server.
                        try
                                  output.writeObject("SERVER>>>"+message);//For Client side.
                                  System.out.println(message);
                                  output.flush();
                                  displayMessage("\nSERVER>>>"+message);//On server side.
                        catch(IOException ioException)
                                  displayMessage("\nError writing object");
              private void displayMessage(final String messageToDisplay)
                        SwingUtilities.invokeLater(
                             new Runnable()
                                  public void run()
                                            displayArea.append(messageToDisplay);
              private void setTextFieldEditable(final boolean editable)
                        SwingUtilities.invokeLater(
                             new Runnable()
                                  public void run()
                                            enterdField.setEditable(editable);
              public static void main(String q[])
                        Server app = new Server();
                        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        app.runServer();
    //Client.class
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class Client extends JFrame
         private JTextField enterField;
         private JTextArea displayArea;
         private ObjectOutputStream output;
         private ObjectInputStream input;
         private String message="";
         private String chatServer;
         private Socket client;
         public Client (String host)
                   super("Client");
                   chatServer=host;
                   enterField = new JTextField();
                   enterField.setEditable(false);
                   enterField.addActionListener(
                        new ActionListener()
                                  public void actionPerformed(ActionEvent event)
                                            sendData(event.getActionCommand());
                                            enterField.setText("");
                        add(enterField,BorderLayout.NORTH);
                        displayArea = new JTextArea();
                        add(new JScrollPane(displayArea),BorderLayout.CENTER);
                        setSize(300,150);
                        setVisible(true);
         public void runclient()
                   try
                             connectToServer();
                             getStreams();
                             processConnection();
                   catch(EOFException eofException)
                             displayMessage("\nClient treminated connection");
                   catch(IOException ioException)
                             ioException.printStackTrace();
                   finally
                             closeConnection();
         private void connectToServer() throws IOException
                   displayMessage("Attempting connection\n");
                   client = new Socket(InetAddress.getByName(chatServer),12345);
                   displayMessage("Connect to:"+client.getInetAddress().getHostName());
         private void getStreams() throws IOException
                   output = new ObjectOutputStream(client.getOutputStream());
                   output.flush();
                   input = new ObjectInputStream(client.getInputStream());
                   //Thread t = new Thread(this,"Thread");
                   //t.start();
                   displayMessage("\nGot I/O stream\n");
         private void processConnection( ) throws IOException
                   setTextFieldEditable(true);
                   do
                             try
                                       message=(String)input.readObject();
                                       displayMessage("\n"+message);
                             catch(ClassNotFoundException classnotfoundexception)
                                       displayMessage("\nUnknown object type received");
                   while(!message.equals("SERVER>>>TERMINATE"));
         private void closeConnection()
                   displayMessage("\n Closing connection");
                   setTextFieldEditable(false);
                   try
                             output.close();
                             input.close();
                             client.close();
                   catch(IOException ioException)
                             ioException.printStackTrace();
         private void sendData(String message)
                   try
                             output.writeObject("CLIENT>>>"+message);
                             //System.out.println(message);
                             output.flush();
                             displayMessage("\nCLIENT>>>"+message);
                   catch(IOException ioException)
                             displayArea.append("\n Error writing object");
         private void displayMessage(final String MessageToDisplay)
                   SwingUtilities.invokeLater(
                        new Runnable()
                                  public void run()
                                            displayArea.append(MessageToDisplay);
         private void setTextFieldEditable(final boolean editable)
                   SwingUtilities.invokeLater(
                        new Runnable()
                                  public void run()
                                            enterField.setEditable(editable);
         public static void main(String q[])
                   Client app;
                   if(q.length==0)
                             app = new Client("127.0.0.1");
                   else
                             app = new Client(q[0]);
                   app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   app.runclient();
    Use this example .....
    Give me reply.My method is correct or not
    All the best

  • SocketPermissions for Chat Server/Client Applet

    Hi,
    I've coded a chat server/client applet and found that I need to set socketpermissions when using over the net.
    I put the following line in my java.policy file under my jdk
    permission java.net.SocketPermission ":6288", "connect,accept, listen";
    but it still tells me:
    java.security.AccessControlException: access denied(java.net.SocketPermission 217.0.0.1:6288 connect, resolve)
    any ideas? or am I doing something wrong?
    Also I havent set anything for my applet, and wouldnt know how to? if you do have to set permissions for that, do you put the permissions in with the code or something?
    Thanks in advance.
    Matt.

    ah, dont worry, I've got it fixed.
    that 217.0.0.1 address is because I typed the error by the way, usually it would have my IP.
    problem was I had forgot to recompile with my new assigned IP, d'oh!

  • Need some help on JAVA CHAT SERVER

    i need some info about java chat server. Please any one who have developed give me the details about the logic and process flow.

    Have you read any of these?
    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2B%22chat+server%22&col=javaforums

  • Trying to produce a java chat server

    Would like produce a working client/server chat system, as basic as possible but able to listen and talk to each other. Any chat servers how-to examples I've come across never seem to work.
    Would like to understand why applets don't work when I open the web page but do work when I view using the appletviewer. I use Internet Explorer 4 i think, java version 1.3.0_02
    would you understand at least part of this error which appears when I run a chat server
    exception:com.ms.security.SecurityExceptionEx[Client.<int>]:cannot access "194.81.104.26":5660
    (the error is all one line no spaces)
    the following code is one of the programs I've been working on and I receive the above error, appletviewer doesn't work so i think that means something is wrong with the code, client side as the server side works well, it listens etc
    // Client side
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    public class Client extends Panel implements Runnable
    // Components for the visual display of the chat windows
    private TextField tf = new TextField();
    private TextArea ta = new TextArea();
    // The socket connecting us to the server
    private Socket socket;
    // The streams we communicate to the server; these come
    // from the socket
    private DataOutputStream dout;
    private DataInputStream din;
    // Constructor
    public Client( String host,int port ) {
    // Set up the screen
    setLayout( new BorderLayout() );
    add( "North", tf );
    add( "Center", ta );
    // Receive messages when someone types a line
    // and hits return, using an anonymous class as
    // a callback
    tf.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    processMessage( e.getActionCommand() );
    // Connect to the server
    try {
    // Initiate the connection
    socket = new Socket( host, port );
    // Recieved a connection
    System.out.println( "connected to "+socket );
    // Create DataInput/Output streams
    din = new DataInputStream( socket.getInputStream() );
    dout = new DataOutputStream( socket.getOutputStream() );
    // Start a background thread for receiving messages
    new Thread( this ).start();
    } catch( IOException ie ) { System.out.println( ie ); }
    // Called when the user types something
    private void processMessage( String message ) {
    try {
    // Send it to the server
    dout.writeUTF( message );
    // Clear out text input field
    tf.setText( "" );
    } catch( IOException ie ) { System.out.println( ie ); }
    // Background thread runs this: show messages from other window
    public void run() {
    try {
    // Receive messages one-by-one, forever
    while (true) {
    // Get the next message
    String message = din.readUTF();
    // Print it to our text window
    ta.append( message+"\n" );
    } catch( IOException ie ) { System.out.println( ie ); }
    // ClientApplet
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    public class ClientApplet extends Applet
    public void init() {
    //String host = getParameter( "host" );
         String host="194.81.104.26";
         //int port = Integer.parseInt( getParameter( "port" ) );
         int port =5660;
    setLayout( new BorderLayout() );
    add( "Center", new Client( host, port ) );
    // server
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Server
    // The ServerSocket is used for accepting new connections
    private ServerSocket ss;
    // A mapping from sockets to DataOutputStreams. This will
    // help us avoid having to create a DataOutputStream each time
    // we want to write to a stream.
    private Hashtable outputStreams = new Hashtable();
    // Constructor and while-accept loop all in one.
    public Server( int port ) throws IOException {
    // listening
    listen( port );
    private void listen( int port ) throws IOException {
    // Create the ServerSocket
    ss = new ServerSocket( port);
    // ServerSocket is listening
    System.out.println( "Listening on "+ss );
    // Keep accepting connections forever
    while (true) {
    // The next incoming connection
    Socket s = ss.accept();
    // Connection
    System.out.println( "Connection from "+s );
    // Create a DataOutputStream for writing data to the
    // other side
    DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
    // Save this stream so we don't need to make it again
    outputStreams.put( s, dout );
    // Create a new thread for this connection, and then forget
    // about it
    new ServerThread( this, s );
    // Get an enumeration of all the OutputStreams, one for each client
    // connected to us
    Enumeration getOutputStreams() {
    return outputStreams.elements();
    // Send a message to all clients (utility routine)
    void sendToAll( String message ) {
    // We synchronise on this because another thread might be
    // calling removeConnection()
    synchronized( outputStreams ) {
    // For each client ...
    for (Enumeration e = getOutputStreams(); e.hasMoreElements(); ) {
    // ... get the output stream ...
    DataOutputStream dout = (DataOutputStream)e.nextElement();
    // ... and send the message
    try {
    dout.writeUTF( message );
    } catch( IOException ie ) { System.out.println( ie ); }
    // Remove a socket, and it's corresponding output stream, from our
    // list. This is usually called by a connection thread that has
    // discovered that the connectin to the client is dead.
    void removeConnection( Socket s ) {
    // Synchronise so sendToAll() is okay while it walks
    // down the list of all output streams
    synchronized( outputStreams ) {
    // Removing connection
    System.out.println( "Removing connection to "+s );
    // Remove it from our hashtable/list
    outputStreams.remove( s );
    // Make sure it's closed
    try {
    s.close();
    } catch( IOException ie ) {
    System.out.println( "Error closing "+s );
    ie.printStackTrace();
    // Main routine
    // Usage: java Server <port>
    static public void main( String args[] ) throws Exception {
    // Get the port # from the command line
    int port = Integer.parseInt( args[0] );
         //int port = 5000;
    // Create a Server object, which will automatically begin
    // accepting connections.
    new Server( port);
    // ServerThread
    import java.io.*;
    import java.net.*;
    public class ServerThread extends Thread
    // The Server that spawned
    private Server server;
    // The Socket connected to our client
    private Socket socket;
    // Constructor.
    public ServerThread( Server server, Socket socket ) {
    // Save the parameters
    this.server = server;
    this.socket = socket;
    // Start up the thread
    start();
    // This runs in a separate thread when start() is called in the
    // constructor.
    public void run() {
    try {
    // Create a DataInputStream for communication; the client
    // is using a DataOutputStream to write to us
    DataInputStream din = new DataInputStream( socket.getInputStream() );
    // Over and over, forever ...
    while (true) {
    // ... read the next message ...
    String message = din.readUTF();
    // ... sending printed to screen ...
    System.out.println( "Sending "+message );
    // ... and have the server send it to all clients
    server.sendToAll( message );
    } catch( EOFException ie ) {
    // This doesn't need an error message
    } catch( IOException ie ) {
    // This needs an error message
    ie.printStackTrace();
    } finally {
    // The connection is closed for one reason or another,
    // so have the server dealing with it
    server.removeConnection( socket );
    <body bgcolor="#FFFFFF">
    <applet code="ClientApplet" width=600 height=400>
    <param name=host value="127.0.0.1">
    <param name=port value="5660">
    [Chat applet]
    </applet>
    </body>

    Hi!
    Go to
    http://www.freecode.com/projects/jchat-java2clientserverchatmodule/
    probably u will het the answer..
    Jove

  • Java chat server . . . help!

    i do macromedia flash and well i downloaded this chat flash java chat. now i know nothing about java, and i do have the sdk and java runtimes. as well as the program bluej. now the guy eho made this chat talks about putting up a server and modifing ports and the like. heres a link of what it says:
    http://guardians_of_vox.tripod.com/readme.txt
    now can anyone tell me what to do or what to get, cause i am a total n00b at this.

    Do you have any specific problems? What have you done? What is not working?

  • Yes, its another chat server/client program

    Im busy writing a chat program and am having a problem figuring out how to show the users that are online. The ChatServer class contains methods for recieving messages, broadcasting messages, accepting new connections etc.
    Im using non-blocking mode and I register all the connections with a Selector. When a new user connects to the server, I add the SocketChannel to a LinkedList which contains all the users that are online.
    My problem is that my ChatServer class runs completly seperatly from any other classes (I presume thats normal?). In other words, I run the ChatServer and once that is running I run the StartGUI class which creates the swing gui and all of that. I then type in the host name etc and connect to the server. So how would I show the users that are online? Even if I can somehow get all the ip addresses then ill figure out how to give 'nicks' and all that from there.
    As I said, I have a line (LinkedList.add(newChannel) which adds the clients to that list which I simply did so that i can display the number of users online. Is there a way I could now manipulate that LinkedList to get all the users and then display them (since it contains a list of all the SocketChannels)? Or would that not be possible?
    If it is possible to get the users from the LinkedList, then the other problem is the fact that the list is created as part of the ChatServer so I cant get to it?
    Another way that I thaught might be possible, is that since I register all the keys with a Selector when a new user is added (this happens in the ChatClient clas), then I might be able to get the users from that but im not sure if thats possible?
          readSelector = Selector.open();
          InetAddress addr = InetAddress.getByName(hostname);
          channel = SocketChannel.open(new InetSocketAddress(addr, PORT));
          channel.configureBlocking(false);
          channel.register(readSelector, SelectionKey.OP_READ, new StringBuffer());Ill add to my explanation if need be, since im very new to this sort of programming. Ill post some more code if need be.
    thanks, R

    Through some more playing around this afternoon ive figured out how im going to solve my problem. It may not be the best way to do it but I think that at least it is going to work.
    Im going to convert the LinkedList to a String and then change that into a ByteBuffer, and use channel.write(ByteBuffer) as if it was any other normal message.
    My logic will be as follows:
    Client: click 'get user list' button --> send String 'get users' to the server using channel.write("get users")
    Server: read the String like any other normal String 'channel.read(ByteBuffer) --> decode the ByteBuffer back into a String --> if the String sais "get users" --> put the LinkedList into a String and then into a ByteBuffer --> send the buffer using channel.write(buffer)
    Client: check the incoming buffer for some or other string (maybe an ip address) that will let it know that it is the list of users and not a normal string. Then use a bit of String manipulation to extract the IP addresses from the String.
    Is this a reasonable way of doing it? Any other ideas?
    Also,...Is it alright to add the linked list to a String and then into a ByteBuffer to send? Since if there are for example 100 users online then it will be quite a big string and therefore there will be a lot going into the buffer and being sent by the server. Are there any potential problems I could run into here with lots of users?
    (lol, its been great talking to myself here ;) , hopefully some of you will have some comments or ideas after the weekend.)
    R

  • Java Chat Servers???

    I hope this isn't an inappropriate query for this forum. I'm looking for a Java Chat Server and was told that Sun/Java provides a free, open source implementation but haven't been able to find it. I've also looked at some of the commercial offerings such as Volano and RealChat. Would anyone like to offer advice on the best options?
    Thanks for any help.

    I've coded my own very basic version but it would be
    much cheaper for my company to buy one than to try
    and do a full-blown, commercial-grade, fully
    de-bugged implementation from scratch or demos, for
    me at least ;-)I'm sure it would be cheaper. I'm sure that chat servers are extremely common, too. By the way, where does Java come into your picture? I don't see any benefit to having a chat server that happened to be written in Java.

  • My simple chat server does not send messages to connected clients

    Hi!
    I´m developing a chat server. But I can not get it work. My client seems to make a connection to it, but my server does not send the welcome message it is supposed to send when a client connects. Why not?
    removedEdited by: Roxxor on Nov 24, 2008 10:36 AM

    Ok, I solved my previous problem and now I have got a new really annoying one.
    This is a broadcasting server which meand it can handle multiple clients and when one client sends a message to the server, the server should broadcast the message to all connected clients. It almost works, except that the server just sends the message back to the last connected client. The last connected client seems to steal the PrintStream() from the other clients. How can I solve that?
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.lang.Character;
    import java.io.OutputStream;
    import java.util.Vector;
    public class ChatServer extends MIDlet implements CommandListener, Runnable
         private Display disp;
         private Vector connection = new Vector();          
         private TextField tf_port = new TextField("Port: ", "", 32, 2);               
         private Form textForm = new Form("Messages");
         private Form start_serverForm = new Form("Start server", new Item[] {  tf_port });
         private Command mExit = new Command("Exit", Command.EXIT, 0);
         private Command mStart = new Command("Start", Command.SCREEN, 0);
         private Command mDisconnect = new Command("Halt server", Command.EXIT, 0);
         ServerSocketConnection ssc;
         SocketConnection sc;
         PrintStream out;
         public ChatServer()
              start_serverForm.addCommand(mExit);
              start_serverForm.addCommand(mStart);
              start_serverForm.setCommandListener(this);
              tf_port.setMaxSize(5);
              textForm.addCommand(mDisconnect);
              textForm.setCommandListener(this);
         public void startApp()
              disp = Display.getDisplay(this);
              disp.setCurrent(start_serverForm);
         public void pauseApp()
         public void destroyApp(boolean unconditional)
         public void commandAction(Command c, Displayable s)
              if(c == mExit)
                   destroyApp(false);
                   notifyDestroyed();
              else if(c == mStart)
                   Thread tr = new Thread(this);
                   tr.start();
              else if(c == mDisconnect)
                   try
                        sc.close();                              
                   catch(IOException err) { System.out.println("IOException error: " + err.getMessage()); }
                   destroyApp(false);
                   notifyDestroyed();
         public void run()
              try
                   disp.setCurrent(textForm);
                   ssc = (ServerSocketConnection)Connector.open("socket://:2000");
                   while(true)               
                        sc = (SocketConnection) ssc.acceptAndOpen();     
                        connection.addElement(sc);                                                  
                        out = new PrintStream(sc.openOutputStream());
                        textForm.append(sc.getAddress() + " has connected\n");
                        ServerToClient stc = new ServerToClient(sc);
                        stc.start();
              catch(IOException err) { System.out.println("IOException error: " + err.getMessage()); }
              catch(NullPointerException err) { System.out.println("NullPointerException error: " + err.getMessage()); }
         class ServerToClient extends Thread
              String message;
              InputStream in;
              SocketConnection sc;
              ServerToClient(SocketConnection sc)
                   this.sc = sc;
              public void run()
                   try
                        in = sc.openInputStream();
                        int ch;
                        while((ch = in.read())!= -1)                         
                             System.out.print((char)ch);
                             char cha = (char)ch;                              
                             String str = String.valueOf(cha);                    
                             out.print(str);
                             //broadcast(str);
                             textForm.append(str);                              
                        in.close();
                        //out.close();
                           sc.close();
                   catch(IOException err) { System.out.println("IOException error: " + err.getMessage()); }
    }

  • Java Server/Client Applicaton - problem with sending data back

    Hello!
    I'm trying to write a small server/client chat application in Java. It's server with availability to accept connections from many clients and it's app just for fun... However, I've come up against a huge problem: everything what clients send, arrives to server (I'm sure about that because it is displayed on the Server Application screen) and then server should send it back to all clients but it doesn't work. I have no faintest idea what causes this problem. Maybe you can help me?
    Here is my server app code:
    import java.net.*;
    import java.util.*;
    import java.io.*;
    * @author Robin
    public class Server {
        ServerSocket serw = null;
        Socket socket = null;
        String line = null;
        Vector<ClientThread> Watki = new Vector();
        ClientThread watek = null;
        public Server(int port) {
            try {
                serw = new ServerSocket(port);           
                line = "";
                while(true) {
                    System.out.println("Running. Waiting for client to connect...");
                    socket = serw.accept();
                    System.out.println("Connected with:\n" + socket.getInetAddress() + "\n");
                    watek = new ClientThread(socket);
                    Watki.addElement(watek);
                    Watki.firstElement().Send("doszlo?");
            }catch (IOException e) {
                System.out.println("BLAD: " + e);
        public void sendToAll(String s) {
            for(int i = 0; i < Watki.size(); i++) {
                Watki.elementAt(i).Send(s);
        public class ClientThread extends Thread {
            Socket socket;
            DataInputStream in = null;
            DataOutputStream out = null;
            String line = null;
            public ClientThread(Socket s) {
                try {
                    this.socket = s;
                    in = new DataInputStream(s.getInputStream());
                    out = new DataOutputStream(s.getOutputStream());
                    start();
                }catch (IOException e) {
                    System.out.println("BLAD: " + e);
            public void Send(String s) {
                try {
                    out.writeUTF(s);
                }catch (IOException e) {
                    System.out.println("BLAD: " + e);
            public void run() {
                try {
                    line = "";
                    while (true) {
                        line = in.readUTF();
                        System.out.println(line);
                        sendToAll(line);
                }catch (IOException e) {
                    System.out.println("BLAD: " + e);
        public static void main(String[] args) {
            Server serwer = new Server(5000);
    }And here is client app code:
    import java.net.*;
    import java.util.*;
    import java.io.*;
    * @author Robin
    public class Client implements Runnable {
        Socket socket = null;
        BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
        DataInputStream in = null;
        DataOutputStream out = null;
        String line = null;
        public Client(String host, int port) {
            try {
                System.out.println("Connecting to " + host + ":" + port);
                socket = new Socket(host, port);
                System.out.println("Connected\nTALK:");
                out = new DataOutputStream(socket.getOutputStream());
                in = new DataInputStream(socket.getInputStream());
                line = "";
                while(!line.toLowerCase().equals(".bye")) {
                    line = keyIn.readLine();
                    Send(line);
            }catch (UnknownHostException e) {
                System.out.println("BLAD: " + e);
            }catch (IOException e) {
                System.out.println("BLAD: " + e);
        public void Send(String s) {
            try {
                out.writeUTF(s);
            }catch (IOException e) {
                System.out.println("BLAD: " + e);
        public void run() {
            String loaded = "";
            try {
                while(true) {
                    loaded = in.readUTF();
                    System.out.println(loaded);
            }catch (IOException e) {
                System.out.println("BLAD: " + e);
        public static void main(String[] args) {
            Client client = new Client("localhost", 5000);
    }By the way, this app is mainly written in English language (text that appears on the screen) however in functions I used Polish language (for example: BLAD - it means ERROR in English). Sorry for that :)

    Yeap, I will change those exceptions later, thanks for advice.
    You asked what's going on with it: both applications start with no errors, but when I write something in client side it should be sent to the server and then forwarded to all connected clients but it stops somewhere. However, I added a one line to the server code
    line = in.readUTF();
    System.out.println(line);
    sendToAll(line); and after it reads message from client (no matter which one) it shows that message on the server side screen, then it should send this message to all clients but it doesn't work in this moment. What's confusing: no errors occurs, so it's rather a mistake in my code, but where?
    Edited by: Robin3D on Sep 30, 2009 9:07 AM

  • Chat Server and Client Design

    Ola,
    I just want to make a simple Chat Program for intranet (LAN). I'm planning to use socket connection. What would be a good design for Chat Program? Both the Client and the Server are Java Application.
    Here is the diagram that I have in mind:
    ---- First the client login to Server:
    [Client A] ----> [Server]
    [Client B] ----> [Server]
    ---- Then Server add client in the container, Server put each connection from client to separate Thread, so it can handle multiple clients.
    ---- Then let's say Client A send message to Client B (or others). Server get the message from Client A, and my problem is how to get the Server to send the message to B. The only way that I know is to make each client act like its own server and listening to certain port number. That way the server can send the incoming message directly to the client.
    [Client A] ------> [Server] -----???---> [Client B]
    At this point I just have the Server listening to a port (ex. 10000). Should I have each client listening to a port number?
    Another design that I have in mind is to have only Server listening to port 10000. And have the client to poll the Server (ex. every 2 seconds) to check whether the server has new message for the client.
    The last design that I was considering is using RMI.
    Which approach that will best fit my case? What is the ideal design for making chat client server program? If you know any URL or Books that explains all these issue, please post them here. Any help will be appreciated.

    My approach (with tcp sockets) was the following:
    The server has two serversockets running.
    The client connects at the first one, which it will use
    for sending (any messages) and receiving a reply from the
    server ( an "ok" confirmation or so) .
    The client then connects at the second serversocket,
    which it uses for listening to the server.
    The second socket then also can be used for "alive" calls
    from the server periodically ( to kick out users, who
    have lost connection silently)
    Also the second socket, of course, is used as broadcast channel.
    Broadcasted messages can contain chat messages, information
    about a user, which has logged in or out ..
    When the server receives a (chat)message from a client, it
    first enters that message in its model and then broadcasts
    this message ( or more generally the changes in its model)
    to all clients including the client, who has
    sent the message, which only displays the message, when he
    has received it back from the server.
    This way, the order of messages displayed is the same for
    all clients - its a sort of synchronization process.
    Also, you don't need different ports ( for anything in principle ).
    Port 80 is enough.
    For multiple connections, you can send an integer as first
    data transfer, which acts as "virtual portnumber" and the
    receiver then can forward the socket to the associated threads.
    One thing to note for the broadcast process is, that you
    can't simply broadcast the messages in a loop, because this
    way, one veeery slow client would slow down the whole
    server. Therefore you will have to use threads for that.
    In the old (jdk1.3) way, the server would create a thread
    for each user who connects at the first serversocket,
    pass the socket (which it gets from the accept() method )
    to that thread, and this thread then would block while
    trying to receive, and after it had received something,
    it would call a synchronized method from the server,
    in which the server datamodel would be updated and
    broadcasts would be started ( in an other thread context ).
    A good way to speed up chat systems with heavy load is
    to use MultiCast sockets. But then you would have to
    use Datagrams (UDP).
    Another problem arises, when you want to go through
    firewalls. RMI has probs, and bidirectional transfer
    isn't allowed (some firewalls allow 1 request followed by
    1 answer and then cut the connection to my knowlegde)
    It's possible, but it's more complicated.

  • 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

  • Lync 2010 client connecting to 2013 persistent chat server

    Since we never had Group Chat in our 2010 environment, I have no idea how it works and now that we have 2013 Persistent Chat, I am struggling with getting the Lync 2010 connected. The 2013 client works just fine as it is integrated into the client. I found
    out Lync 2010 needs a separate Chat client to run along side the IM client.
    I installed this client but from there I have no idea how to connect it to the 2013 Chat server. I created the endpoint on the Lync 2013 server according to the article
    http://technet.microsoft.com/en-us/library/jj204901.aspx but something else needs to be done. I just don't know what. Not even sure where to start looking. Many of our Lync clients have
    to use 2010 because the OS is XP so I need to find out how to get these users to work with Persistent Chat.
    I am not sure what the point is of creating the End point according to the article. I am sure its necessary but not sure how it fits into the clients using it to connect. What does the article mean when it says "Next, configure Persistent Chat clients
    to use that SIP address as their contact object". Do you need Group Chat functioning in 2010 for this to even work?
    The problem is we never had Group Chat with 2010 so I am sure there are some settings missing like DNS records etc...

    If you have users running legacy clients (such as Microsoft Lync 2010 these users might find the default Persistent Chat URIs difficult to work with and difficult to use when pointing their legacy client towards the pool. Because of this,
    administrators need to use the New-CsPersistentChatEndpoint cmdlet to create an additional contact object for the pool, a contact object that provides a friendlier, easier-to-use URI.
    Lisa Zheng
    TechNet Community Support

  • After installing Final cut server client on OSX 10.6.8 error: Apple QuickTime or the QuickTime Java component is not installed.

    After installing Final cut server client on OSX 10.6.8 error: Apple QuickTime or the QuickTime Java component is not installed.
    I know this error on windows machines but cannot get a solution for OSX.

    I have fixed this by installing the latest combo update

  • Multiple client chat server

    Thanks to the help I got from the good people of this forum today I modified the chat server program which I am making and now it is working a bit better. Right now it can accept several (up to 8) clients and store their open sockets in a SocketCollection list which can later be accessed so that messages get sent to all of them. Problem is that when I send a message, it is displayed instantaneously on the client that sent that message (my machine), but is displayed only after the other clients press enter on the other clients' machines (for testing purposes it was the same machine, different port opened for communication with server which is also on the same machine). To clarify that - all clients and server are the same machine (that shouldn't be a problem, right?). Code for printing incoming data for client program is below:
    while ((fromServer = in.readLine()) != null) {
                if (fromServer!=null){
                       System.out.println(fromServer);
                       System.out.println("print on client screen msg received from server");
                fromUser = stdIn.readLine();
                if (fromUser != null) {
              System.out.println("Client: " + fromUser);
              out.println(fromUser);
    }Code to deliver the message to all clients from the server application is below as well:
    while ((inputLine = in.readLine()) != null) {
                     PrintWriter multiOut;
                   for (int x=0; x<8; x++){
                         System.out.println("INSIDE MULTI-TELL FOR LOOP");
                         if (socketCollection[x]!=null){
                               Socket c=socketCollection[x];
                               try{
                                   System.out.println("tried to send to all\nSocket c = " + c);
                                   out=new PrintWriter(c.getOutputStream(), true);
                                       out.println(c.getInetAddress() + inputLine);
                                catch(IOException ioe){}
    }In the server's DOS window I can clearly see that it enters to display the message to multiple clients and it should send it. The sockets are all different and they point to different ports on different clients' machines. Maybe the problem is just in the client program's code. If you could help me out, it will be greatly appreciated. Thank you very much.

    The sockets get created one by one when each client connects. Afterwards when the thread is made, that socket gets copied into the SocketCollection array which can afterwards be accessed in order for the server to distribute the message to all its connected clients.
    The for loop in the second code example where it takes SocketCollection[x] and gets its outputStream and all that is where it prints the message and sends it to each client (sends it but it is not displayed on the client side until the client sends a message to the server again). My question is how to make it so the client does not have to send a message in order to see the server message (message to all clients) that was sent before.

Maybe you are looking for