Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

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.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900