Click here to Skip to main content
14,301,527 members
Rate this:
Please Sign up or sign in to vote.
See more:
i got some trouble in the general idea of client/server,like as the client i send the numbers to the server,then somehow i need to stop the client program and execute the server and then reverse,i dont understand how to do that.


to explain the code theres an application on a jframe with awt components ,when i click button1 it needs to send data to the server and execute

What I have tried:

private void button1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        try {
            
            ServerSocket server = new ServerSocket(8888); 
            Socket connectionToTheServer =  new Socket("localhost", 8887);
            OutputStream out = connectionToTheServer.getOutputStream();
            PrintStream ps = new PrintStream(out, true); 
            ps.println(textField1);
            ps.println(textField3);
            InputStream in = connectionToTheServer.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String a = br.readLine();
            JOptionPane.showMessageDialog(null, a);
        } catch (IOException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                       

                              
    public static void main(String args[]) throws IOException {
        ServerSocket server = new ServerSocket(8888);
        Socket connectionToTheClient = server.accept();
        NewJFrame.main(args);
        InputStream in = connectionToTheClient.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        int nrF = 0;
        int nrS = 0;
        int sum = 0;
        String line = br.readLine();
        nrF = Integer.parseInt(line);
        line = br.readLine();
        nrS = Integer.parseInt(line);
        sum = nrF+nrS;
        OutputStream out = connectionToTheClient.getOutputStream();
PrintStream ps = new PrintStream(out, true); 
ps.println(sum);
}
Posted
Updated 23-Aug-19 22:27pm
v2
Comments
OriginalGriff 23-Aug-19 11:19am
   
And?
What does it do that you didn't expect, or not do that you did?
Where are you stuck?
What have you tried?
What help do you need?

In short: what is the problem?

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

You appear to be trying to run both client and server code in the same thread. Take a look at javanetexamples[^] for an example of how it could be done.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100