Multiple client to server communication program in Java

前端 未结 3 1094
南旧
南旧 2020-12-14 21:33

I wrote a server-client communication program and it worked well.

Client module

import java.io.*;
import java.net.*;

class Client {
    public sta         


        
相关标签:
3条回答
  • 2020-12-14 22:09

    MainServer class

    public class Server {
    
        public static void main(String[] args) throws IOException {
    
            ServerSocket serverSocket = null;
    
            boolean listeningSocket = true;
            try {
                serverSocket = new ServerSocket(2343);
            } catch (IOException e) {
                System.err.println("Could not listen on port: 2343");
            }
    
            while(listeningSocket){
                Socket clientSocket = serverSocket.accept();
                MiniServer mini = new MiniServer(clientSocket);
                mini.start();
            }
            serverSocket.close();       
        }
    
    }
    

    Helper Class

    public class MiniServer extends Thread{
    
        private Socket socket = null;
    
        public MiniServer(Socket socket) {
    
            super("MiniServer");
            this.socket = socket;
    
        }
    
        public void run(){
                //Read input and process here
        }
                //implement your methods here
    
    }
    
    0 讨论(0)
  • 2020-12-14 22:22

    Well, when I do something like that, I implement a listener that manages the server side, so when a client (the client won't probably need changes) connects, the server launch one thread to work with that client.

    while (!stop)
                {
                    socket = serverSocket.accept();
                    HiloSocket hiloSocket = new HiloSocket(socket, this);
                    hiloSocket.start();
                }
    

    Of course, HiloSocket extends Thread and it has the logic behind to manage the client...

    0 讨论(0)
  • 2020-12-14 22:25

    You want to look into Java concurrency. That's the concept of one Java program doing multiple things at once. At a high level you will be taking your while(true) { //... } block and running it as part of the run() method of a class implementing Runnable. You'll create instances of Thread that invoke that run() method, probably one per client you expect.

    For a really good, deep understanding of all that Java offers when it comes to concurrency, check out Java Concurrency in Practice.

    0 讨论(0)
提交回复
热议问题