Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Java Socket - Server, how to implement in GUI?

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Location
    Belgrade, Serbia.
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Java Socket - Server, how to implement in GUI?

    First of all, hello everybody, I'm new here

    I'm making communication between two java programs, server and client. Main thing that they should do is some encrypting, but that is not problem. I'v kinda "stolen" chat communication from one of the best youtube explanations and removed some unnecessary parts. Communication is working great, client is working great and server is working great AS LONG as I keep him away from GUI.

    When server is class it self, and when I'm starting program from main class, it works great, writing down on console everything I want, but when i put that in swing GUI (default, created with netbeans) and try to start server from button click, I get frozen gui. Ok, I was thinking, since server has two "while(true)" loops, one for accepting connections and one for reading, I just should put him in new thread and that should do it. When I do that, I don't get frozen GUI, but I can't show anything on my server GUI from server it self. Server is working, it's printing everything in console: for example
    System.out.println(data[0] + " has connected.");
    where data[0] is ip address of client, but if i just add
    System.out.println(data[0] + " has connected."); 
    console.setText("User has connected");
    where console is my JTextArea in GUI, it won't append. I'v tried a lot of approaches but I can't get it working...


    I'll get you guys here just server code with main class:
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.math.BigInteger;
     
    public class Test2Server {
        ArrayList clientOutputStreams;
        ArrayList<String> onlineUsers = new ArrayList();
     
        public class ClientHandler implements Runnable{ 
    	BufferedReader reader;
    	Socket sock;
            PrintWriter client;
            public ClientHandler(Socket clientSocket, PrintWriter user) {
                // new inputStreamReader and then add it to a BufferedReader
                client = user;
                try {
    		sock = clientSocket;
    		InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
    		reader = new BufferedReader(isReader);
                } // end try
                catch (Exception ex) {
    		System.out.println("error beginning StreamReader");
                } // end catch
    	} // end ClientHandler()
     
    	public void run() {
                String message;
                String[] data;
                String connect = "Connect";
                String disconnect = "Disconnect";
                String chat = "Chat";
                String diffie = "Diffie";
     
     
                try {
    		while ((message = reader.readLine()) != null) {
     
                        data = message.split("¥");   
     
                        if (data[2].equals(connect)) {
                            userAdd(data[0]);
                            System.out.println(data[0] + " has connected.");
                        } 
                        else if (data[2].equals(disconnect)) {
                            userRemove(data[0]);
                            System.out.println(data[0] + " has disconnected.");
                        } 
                        else if (data[2].equals(chat)) {
                            tellEveryone(message);
                        } 
                        else if (data[2].equals(diffie)){
                            System.out.println(data[1]);
                        }
                        else {
                            System.out.println("No Conditions were met.");
                        }
                    } // end while
                } // end try
                catch (Exception ex) {
                    System.out.println("lost a connection");
                    clientOutputStreams.remove(client);
                } // end catch
    	} // end run()
    } // end class ClientHandler
     
        public void userAdd (String data) {
            String message;
            String add = "¥ ¥Connect";
            String done = "Server¥ ¥Done";
            onlineUsers.add(data);
            String[] tempList = new String[(onlineUsers.size())];
            onlineUsers.toArray(tempList);
            for (String token:tempList) {      
                message = (token + add);
                tellEveryone(message);
            }
            tellEveryone(done);
        }
     
        public void userRemove (String data) {
            onlineUsers.remove(data);
        }
     
        public void tellEveryone(String message) {
    	Iterator it = clientOutputStreams.iterator();
            while (it.hasNext()) {
                try {
                    PrintWriter writer = (PrintWriter) it.next();
    		writer.println(message);
                    writer.flush();
                }
                catch (Exception ex) {
    		System.out.println("error telling everyone");
                }
    	}
        }
     
     
     
    //------------------------------------main-------------------------------------
        public static void main(String args[]){
            new Test2Server().go();
        }
        public void go() {
            clientOutputStreams = new ArrayList();
    	try {
                ServerSocket serverSock = new ServerSocket(5000);
                while (true) {
                    // set up the server writer function and then begin at the same
                    // the listener using the Runnable and Thread
                    Socket clientSock = serverSock.accept();
                    PrintWriter writer = new PrintWriter(clientSock.getOutputStream());
    		clientOutputStreams.add(writer);
     
    		// use a Runnable to start a 'second main method that will run
    		// the listener
    		Thread listener = new Thread(new ClientHandler(clientSock, writer));
    		listener.start();
    		System.out.println("got a connection");
                } // end while
    	} // end try
    	catch (Exception ex){
                System.out.println("error making a connection");
            } // end catch
        } // end go()  
    }
    where you can see that I'm starting server from main method. My question is, what's the best way to implement that server in GUI?
    This is my first post on this forum so I'm sorry if I'm doing something wrong.

    Thanks.


  2. #2
    Junior Member
    Join Date
    Jun 2012
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Java Socket - Server, how to implement in GUI?

    I did something similar to this with a basic chat client. Here is the code I used for the Client. The host uses the same method for displaying information received in a GUI.


    package tcpechoclientgui;
     
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.Socket;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
     
    public class TCPEchoClientGUI extends JFrame
    {
      public static void main(String[] args)
      {
        if ((args.length < 1) || (args.length > 2))
          throw new IllegalArgumentException("Parameter(s): <Server> [<Port>]");
     
        String server = args[0]; // Server name or IP address
        System.out.println(server);
        int servPort = (args.length == 2) ? Integer.parseInt(args[1]) : 7;
        System.out.println(servPort);
     
    //creating JFrame
        JFrame frame = new TCPEchoClientGUI(server, servPort);
        frame.setVisible(true);
      }
     
      public TCPEchoClientGUI(String server, int servPort)
      {
        super("TCP Echo Client"); // Set the window title
        setSize(300, 300); // Set the window size
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
        // JText Field to be used for information being sent out
        final JTextField echoSend = new JTextField();
        getContentPane().add(echoSend, "South");
     
        // JTextArea to display received information
        final JTextArea echoReply = new JTextArea(8, 20);
     
        echoReply.setEditable(false);
     
    //make text area scrollPane
        JScrollPane scrollPane = new JScrollPane(echoReply);
        getContentPane().add(scrollPane, "Center");
     
        final Socket socket; // Client socket
        final DataInputStream in; // Socket input stream
        final OutputStream out; // Socket output stream
        try
        {
          // Create socket and fetch I/O streams
          socket = new Socket(server, servPort);
     
     
          in = new DataInputStream(socket.getInputStream());//this is information being received
          out = socket.getOutputStream();
          echoSend.addActionListener(new ActionListener()
          {
            public void actionPerformed(ActionEvent event)//listener for echoSend
            {
              if (event.getSource() == echoSend)
              {
                byte[] byteBuffer = echoSend.getText().getBytes();
                try
                {
                  out.write(byteBuffer);
                  in.readFully(byteBuffer);
     
    //adds what was sent and received to the JTextField
                  echoReply.append(new String(byteBuffer) + "\n");
                  echoSend.setText("");
                }
                catch (IOException e)
                {
                  echoReply.append("ERROR\n");
                }
              }
            }
          });
     
          addWindowListener(new WindowAdapter()
          {
            public void windowClosing(WindowEvent e)
            {
              try
              {
                socket.close();
              }
              catch (Exception exception)
              {
              }
              System.exit(0);
            }
          });
        }
        catch (IOException exception)
        {
          echoReply.append(exception.toString() + "\n");
        }
      }
    }

  3. #3
    Junior Member
    Join Date
    Aug 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Socket - Server, how to implement in GUI?

    What is java orbit server??

  4. #4
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Java Socket - Server, how to implement in GUI?

    Quote Originally Posted by Muheeb.faizan View Post
    What is java orbit server??
    You might want to ask this question in its own thread rather than hijack someone else's. I've heard that it doesn't cost nuthin'.

Similar Threads

  1. Java socket server problem
    By Lionlev in forum Java Networking
    Replies: 6
    Last Post: May 27th, 2012, 11:22 AM
  2. Re: Java socket server problem
    By viperhastle in forum Java Networking
    Replies: 1
    Last Post: May 27th, 2012, 11:21 AM
  3. Sending zip from server socket
    By moon_werewolf in forum Java Theory & Questions
    Replies: 0
    Last Post: May 30th, 2011, 07:51 AM
  4. Replies: 0
    Last Post: February 24th, 2011, 06:31 AM
  5. client/server socket
    By Java_dude_101 in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: January 18th, 2011, 01:16 AM