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!

Similar Messages

  • Server thread for Chat server error

    hey i am trying to make a server for a simple chat service..i have written the code for the server but in my ChatServer thread in the run() function it is giving a null pointer exception...please help me out in this as unless the server is not running i can procede on checking my client code.
    i am attaching the code for my ChatServer.java
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.io.DataOutputStream;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.io.IOException;
    import java.lang.Thread;
    @SuppressWarnings("unused")
    public class ChatServer extends Thread
         Thread thread;
         Socket socket;
         ServerSocket serversocket;
         ArrayList<ClientObj> userarraylist;
         @SuppressWarnings("unchecked")
         ArrayList messagearrayList;
         ClientObj clientobject;
         public ChatServer()
         @SuppressWarnings("unchecked")
         public void StartServer()
         try{     
         serversocket = new ServerSocket(4567);
         }catch(IOException e) { }
          userarraylist = new ArrayList();
          messagearrayList = new ArrayList();
         thread = new Thread(this);
         thread.start();     
         public void run()
              while(true)
                   try{
                   socket = serversocket.accept();     //I AM GETTING AN EXCEPTION HERE
                   System.out.println("Waiting for connection");
                   }catch(IOException e) { }
                   ChatFunctionality chatFunc = new ChatFunctionality(this,socket);
         public ClientObj GetClientObject(String UserName)
              ClientObj returnClientObject = null;
              ClientObj TempClientObject;
              int m_userListSize = userarraylist.size();
              for(int j = 0; j < m_userListSize; j++)
                   TempClientObject = (ClientObj) userarraylist.get(j);
                   if(TempClientObject.getUserName().equalsIgnoreCase(UserName))
                        returnClientObject = TempClientObject;
                        break;
              return returnClientObject;
         public boolean IsUserExists(String UserName)
              if(GetClientObject(UserName) != null)
                   return true;
              else
                   return false;     
         public void SendMessageToClient(Socket clientsocket,String message)
              String sSentence = message;
              try{
              DataOutputStream outToClient = new DataOutputStream(clientsocket.getOutputStream());               
              outToClient.writeBytes(sSentence + '\n');
              }catch(IOException e) { }
         public void AddUser(Socket clientSocket,String UserName)
              if(IsUserExists(UserName))
                   SendMessageToClient(clientSocket,"EXISTS");
                   return;     
              clientobject = new ClientObj(clientSocket,UserName);
              userarraylist.add(clientobject);
         public void SendListOfUsers(Socket clientSocket)
              int listCount = userarraylist.size();
              for(int i=0;i<listCount;i++)
                   String name =  userarraylist.get(i).ClientUserName;
                   SendMessageToClient(clientSocket,name );
         public void SendMessageToAll(String Message)
              int UserCount = userarraylist.size();
              for(int k=0;k<UserCount;k++)
                   ClientObj TempClient = userarraylist.get(k);
                   SendMessageToClient(TempClient.Clientsocket,Message);
         public static void main(String[] args)
              ChatServer chatserver = new ChatServer();
              chatserver.StartServer();
              return;
    }

    So lets have a look at your error.
    java.net. --------------->BindException<-------------------: Address already in use: JVM_Bind
         at java.net.PlainSocketImpl.socketBind(Native Method)
         at java.net.PlainSocketImpl.bind(Unknown Source)
         at java.net.ServerSocket.bind(Unknown Source)
         at java.net.ServerSocket.<init>(Unknown Source)
         at java.net.ServerSocket.<init>(Unknown Source)
         at ChatServer.StartServer(ChatServer.java:36)
         at ChatServer.main(ChatServer.java:132)It clearly states that you have an [BindException. |http://java.sun.com/j2se/1.4.2/docs/api/java/net/BindException.html] So now we go to the java api and look up BindException to find out what it is. And after a have found out what it is, we fix the problem.
    Tell me how you solve the problem after reading what it is.(A hint, try: 4444)
    EDIT: After checking with NETSTAT command in windows cmd, I dont find port 4567 being used.. So it might not be the reason. But it sertainly is worth a try.
    Edited by: prigas on Jul 6, 2008 1:15 AM

  • 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

  • O.S. / Hard Drive Size for NIO Server/Client's load testing...

    Hi All
    I am currently load testing a NIO Server/Client's to see what would be the maximum number of connections that could reached, using the following PC: P4, 3GHz, 1GB RAM, Windows XP, SP2, 110 GB Hard Drive.
    However, I would like to test the Server/Client performance on different OS's:
    Which would be the best possible option from the following:
    1. Partition my current drive, (using e.g. Partition Magic), to e.g.
    - Win XP: 90 GB
    - Win Server 2000: 10 GB
    - Linux: 5 GB
    - Shared/Data: 5 GB
    2. Install a separate Hard drive with the different hard drives
    3. Use a disk caddie, to swap in/out test hard drives.
    4. Any thing else?
    - Would the Operating System's hard drive size affect the Server/Client's performance, e.g. affecting the number of connections, number of File Handles, the virtual memory, etc.?
    Many Thanks,
    Matt

    You can use a partition on the same HDD or use a second HDD, disk caddie well if its a direct IDE or SCSI. If its usb no it will be too slow, may be if you have a fire-wire but I still don't recommend it.
    Be careful if you don't have any experience installing Linux you may do multiple partitions on you disk without knowing, because Linux ext partitions are not visible to windows.
    Recommended disk size for fedora is 10 GB. This is the amount of data that will be created on you HDD when you do a full installation.

  • Simple Server/Client Applet example code ???

    Hi to all.
    I would like to ask if possible to someone to tell me some example code to do this simple thing:
    I want an applet showing only a TextField and a button. When the user writes something on the textfield and press the button, it should send the text in the textfield to the "server", and then it should save it in a variable.
    I think there should be 2 different classes at least (server and client), but no idea in how could I make this on Java.
    So I am asking if possible for some sample code for make this.
    Thank you for the information
    John

    hello!
    Here is a console based Server which will recieve the string and disply on the DOS screen.
    /////////////////////////////////// Server /////////////////
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class ChatServer extends Thread
    ServerSocket ssSocket;
    Socket sSocket;
    public BufferedReader in;
    public PrintWriter out;
    public ChatServer()
         try
         ssSocket = new ServerSocket (4000);
         catch(IOException e)
         System.out.println (e);
    public void run()
    try
         sSocket = ssSocket.accept();
         if(sSocket != null)
              in = new BufferedReader(new InputStreamReader(sSocket.getInputStream()));
              out = new PrintWriter(sSocket.getOutputStream(), true);
    String str = in.readLine();
         System.out.println (str);
         catch(IOException e)
              System.out.println (e);
    public static void main (String []args)
              Thread th = (Thread) new ChatServer();
              th.start();     
    ///////////////////////// Client //////////////////////
    public class Client extends Applet implements ActionListener
    public Socket sClient;
    public BufferedReader in;
    public PrintWriter out ;
    String str;
    private TextField txt = new TextField();
    private Button btn = new Button ("OK");
    public void init()
         try
         sClient = new Socket ("localhost" , 4000);
         in = new BufferedReader(new InputStreamReader(sClient.getInputStream()));
         out = new PrintWriter(sClient.getOutputStream(), true);
         catch (UnknownHostException uhe)
         catch (IOException ioe)
         System.out.println (" I/O Exception : " + ioe);
         setLayout(new FlowLayout());
         txt.setColumns (20);
         add(txt);
         add(btn);
         btn.addActionListener(this);
    public void actionPerformed(ActionEvent AE)
         if(AE.getSource() == btn)
         str = txt.getText();
         out.println(str);
    now u should try it and improve it according to ur need...
    Ahmad Jamal.

  • Server/Client applet sample code ???

    Hi to all.
    I would like to ask if possible to someone to tell me some example code to do this simple thing:
    I want an applet showing only a TextField and a button. When the user writes something on the textfield and press the button, it should send the text in the textfield to the "server", and then it should save it in a variable.
    I think there should be 2 different classes at least (server and client), but no idea in how could I make this on Java.
    So I am asking if possible for some sample code for make this.
    Thank you for the information
    John

    here is code for applet..
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    public class MyApplet extends Applet
          implements ActionListener {
      TextField tf;
      Button btn;
      public void init() {
        setLayout(null);
        tf = new TextField();
        tf.setBounds(5,5,80,20);
        btn = new Button("send message to server");
        btn.setBounds(5,30,150,20);
        btn.addActionListener(this);
        add(tf);
        add(btn);
      public void actionPerformed(ActionEvent ae) {
        sendMessage();
      void sendMessage() {
        String msg = tf.getText().trim();
        tf.setText("");
        if(msg==null) return;
        try {
          // this is using a direct socket connection..
          Socket s = new Socket("www.blah.com",80);
          ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(s.getOutputStream()));
          oos.writeObject(msg);
          oos.flush();
          ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(s.getInputStream()));
          String response = (String) ois.readObject();
          System.out.println("response received="+response);
          ois.close();
          oos.close();
          s.close();
        } catch (Exception e) {
            System.out.println("error in sendMessage:"+e);
    }here is the html code..
    <applet code=MyApplet width=180 height=55></applet>
    let me know if u need more help.
    good luck.

  • 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 (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

  • Applet like chat server

    Hi!
    I`m trying to do a chat server in applet whith sockets. I changed a chat server aplication to a applet but this server joing the browser.
    Is possible to do this? If not, how can i do a applet to talk whith another (peer-to-peer) without use socket?
    thanks for any help!
    Alexandre Camy

    Use a Servlet or JSP on the webserver to transmit messages from one peer applet to another applet

  • 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

  • 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.

  • Client Applet and EJB Server problem

    Hi,
    I developed a applet client that tries to connect to an EJB on the server side. The Applet runs okay in JDev3 but if I deploy it and test it outside the JDev tool I get an error. I tracked the problem to the following line of code:
    ic = new InitialContext(environment);
    Do I run into an applet security problem? If so what do i have to do to allow the applet to read/write to the local system?
    Thanks for any hints!
    Peter
    Error I get
    JAR cache enabled.
    Opening http://pete/gateway/clientmanagement.jar no proxy
    CacheHandler file name: C:\WINNT\Profiles\peter.000\Temporary Internet Files\Content.IE5\ALMN6PAZ\clientmanagement[1].jar
    Creating an initial context
    Opening http://pete/gateway/oracle/oas/container/nls/Version_en_US.class no proxy
    CacheHandler file name: null
    null

    Hi,
    I have still problems getting the client applet running. I tested it with the appletviewer and I modified the security.policy file. I allow the applet to almost everthing but i still get the following error:
    What do I do wrong? Do I really have to sign the jar file? Do I miss some stub classes?
    Thanks for any hints...
    Peter
    JAR cache disabled.
    Opening http://pete/Gateway/. no proxy
    Opening http://pete/Gateway/. no proxy
    Opening http://pete/Gateway/test/Client.class no proxy
    CacheHandler file name: C:\WINNT\Profiles\peter.000\Temporary Internet Files\Content.IE5\ALMN6PAZ\Client[1].class
    Opening http://pete/Gateway/test/Client$1.class no proxy
    CacheHandler file name: C:\WINNT\Profiles\peter.000\Temporary Internet Files\Content.IE5\ALMN6PAZ\Client$1[1].class
    Creating an initial context
    Looking for the EJB published as 'Gateway/GatewayProcessorRemote'
    Opening http://pete:80/_RMProxyURL_ no proxy
    Naming exception!
    [Root exception is org.omg.CORBA.NO_IMPLEMENT: minor code: 0 completed: No]javax.naming.ServiceUnavailableException
    at oracle.oas.jndi.oas.SecCosNamingContext.resolve(SecCosNamingContext.java:265)
    at oracle.oas.jndi.oas.BeanContext.lookup(BeanContext.java:328)
    at oracle.oas.jndi.oas.BeanInitialContext.resolve(BeanInitialContext.java:265)
    at oracle.oas.jndi.oas.BeanContext.lookup(BeanContext.java:328)
    at oracle.oas.jndi.oas.BeanInitialContext.lookup(BeanInitialContext.java:165)
    at oracle.oas.jndi.oas.WrapperContext.lookup(WrapperContext.java:78)
    at oracle.oas.jndi.oas.BeanContext.lookup(BeanContext.java:422)
    at javax.naming.InitialContext.lookup(InitialContext.java:288)
    at test.Client.initializeEJB(Client.java:104)
    at test.Client.startButton_actionPerformed(Client.java, Compiled Code)
    at test.Client$1.actionPerformed(Client.java:55)
    at java.awt.Button.processActionEvent(Button.java:308)
    at java.awt.Button.processEvent(Button.java:281)
    at java.awt.Component.dispatchEventImpl(Component.java, Compiled Code)
    at java.awt.Component.dispatchEvent(Component.java, Compiled Code)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java, Compiled Code)
    at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java, Compiled Code)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:92)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:83)
    null

  • 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.

  • Best thread method for a chat server

    What would be the best way to thread a chat server in Java? I understand threads, but I'm new to java. I'm just looking for links to the appropriate classes not code. I already have the send/receive methods planed, but I'm interested in the best ways to pool the clients once connected.

    class: Thread
    interface: Runnable
    The two items above are what you need.

  • Private Chat functionality for basic server

    Dear all
    Firstly i hope this is the best forum for my question.
    I've written a basic chat server and client. The server recieves strings messages, and broadcasts them to everyone connected to it. I was wandering, sticking with exchanging Strings over the connection, what ways could I implement a private chat facility so one client could choose to send a message that would only be seen by one chosen user?
    Dwarfer

    Hi georgernc
    I completly agree with you. I had originally used the smack api to create a client that talked with an openfire server, however was told (as i'm doing this to create an experiement for a project) that what i was writing was too 'heavy', as there was no need for using things like rooms and roosters) which to be honest is probably true.
    So i went back to just writing a very basic server, with not authentication or security (i don't think i really need security as it will never be used outside of a closed network, and even then it will only be used for short periods of time) that just listens for a connection on serverSocket.accept(), reads from it when there is a message(String) arrives and then broadcast that mesage to all those connected to the server.
    I'm not too sure how to progress in setting up the private chat facility without using smack and openfire (as i've been told not too). I'm going to get cracking and start playing around and see what i can come up...

Maybe you are looking for

  • How do I delete cascade with a PL/SQL procedure?

    This script will create a PL/SQL procedure that deletes cascade. This is a post to contribute to the Oracle community. Take the code as is and test it before you use it in production. Make sure this is what you want. Procedure Delete Cascade (prc_del

  • Exit or BADI for PO lines consolidation

    Hi experts, I have this requirement from one customer: They want a user-exit or BADI that consolidates to lines from a PO. It should work like this: if you add a position with a material number that is already in another position, the exit should add

  • How to use ActiveX Microsoft Office Excel Chart?

    Does anyone know how to use "ActiveX Microsoft Office Excel Chart" from CVI 7.0? I tried with following code but it did not draw anything. HRESULT MakeChartInExcelActivexCtrl(void) HRESULT error = 0; char szErrMsg[256]; // Create a new chart with its

  • SSL implementation on portal development

    Hi, All I have implemented SSL on QA using the standard port 443 and it is working fine.I did the same SSL implementation on portal development using the same port 443 and it doesn't work.When I call up the https url from IE for my portal development

  • Why Here must add a Catch Block ??

    import java.io.*; public class C{      public void test(){           try{                System.out.println("print in try");                throw new FileNotFoundException();           }catch(FileNotFoundException e){                System.out.printl