简体   繁体   中英

How A ,B and S communicate in java in Socket programming?

How client A send message to Client B and B send Message to Server S.And also how communication takes place between A and B?I have tried and solved problem for two party ie single client and single server. I have tried in the following way

//Server
public class DateServer {

    public static void main(String[] args) throws IOException {
        ServerSocket listener = new ServerSocket(9090);
        try {
            while (true) {
                Socket socket = listener.accept();
                System.out.println("Waiting for client on port " +
                    listener.getLocalPort() + "...");

                try {
                    PrintWriter out =
                        new PrintWriter(socket.getOutputStream(), true);
                    out.println(new Date().toString());
                } finally {
                    socket.close();
                }
            }
        } finally {
            listener.close();
        }
    }
}

//Client
public class DateClient {
    public static void main(String[] args) throws IOException {
        String serverAddress = JOptionPane.showInputDialog(
            "Enter IP Address of a machine that is\n" +
            "running the date service on port 9090:");
        Socket s = new Socket(serverAddress, 9090);
        BufferedReader input =
            new BufferedReader(new InputStreamReader(s.getInputStream()));
        String answer = input.readLine();
        JOptionPane.showMessageDialog(null, answer);
        //System.exit(0);
        System.out.println(answer);
    }
}

How communication takes palce between client in java socket programming . But i am not getting idea how communication takes place between A , B and SI have tried too much but not succeeded.I waiting for best answer

Use the MultiThreading concept. You can create two threads in server for accepting the incoming connections from A and B. you need to open two ports in server for clients A and B.

The architecture depends on your need. If you want to establish a connection from X to Y, then Y needs to have a listening port. Thus B needs to listen for incoming connections. Just like S. S needs to listen for incoming traffic as well

Note that this is just one case. The architecture would depend on your requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM