InformationTechnology
InformationTechnology

Reputation: 37

Client-Server connection

I have a java program that will connect the client to the server. This includes making a file directory once the client had triggered the server through sending a message. For example: Once the server is running already, the client will then connect and will send a msg i.e "Your message: Lady", the server will receive a message like "Request to create a Directory named: Lady", after this a directory will be created named Lady.

But the problem is this connection is only for one-to-one. Like only one client can connect to the server...

This is the sample code:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package today._;

import java.io.*;

import java.net.*;

import java.text.*;

import java.util.*;

public class myServer {

    protected static final int PORT_NUMBER = 55555;

    public static void main(String args[]) {

        try {

            ServerSocket servsock = new ServerSocket(PORT_NUMBER);

            System.out.println("Server running...");

            while (true) {
                Socket sock = servsock.accept();
                System.out.println("Connection from: " + sock.getInetAddress());
                Scanner in = new Scanner(sock.getInputStream());
                PrintWriter out = new PrintWriter(sock.getOutputStream());
                String request = "";
                while (in.hasNext()) {
                    request = in.next();
                    System.out.println("Request to Create Directory named: " + request);

          if(request.toUpperCase().equals("TIME")) {  
                    try {
                        File file = new File("C:\\" + request);
                        if (!file.exists()) {
                            if (file.mkdir()) {
                                System.out.println("Directory is created!");
                            } else {
                                System.out.println("Failed to create directory!");
                            }
                        }
                    } catch (Exception e) {
                        System.out.println(e);
                    }
                    out.println(getTime());

                    out.flush();
          } else {
               out.println("Invalid Request...");                     
               out.flush();
          }
                }

            }


        } catch (Exception e) {
            System.out.println(e.toString());
        }

    }

    protected static String getTime() {
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        Date date = new Date();
        return (dateFormat.format(date));
    }
}

package today._;

import java.io.*;

import java.net.*;

import java.util.*;

 public class myClient {

        protected static final String HOST = "localhost";
        protected static final int PORT = 55555;

        protected static Socket sock;

        public static void main(String args[]) {

        try {

              sock = new Socket(HOST,PORT);

              System.out.println("Connected to " + HOST + " on port " + PORT);

              Scanner response = new Scanner(sock.getInputStream());
              PrintWriter request = new PrintWriter(sock.getOutputStream());
              BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
              String txt = "";

              while(!txt.toUpperCase().equals("EXIT")) {

                    System.out.print("Your message:");
                    txt = in.readLine();

                    request.println(txt);
                    request.flush();

                    System.out.println(response.next());

              }

              request.close();
              response.close();
              in.close();
              sock.close();

           } catch(IOException e) {
              System.out.println(e.toString());
           }
      }

 }

Upvotes: 2

Views: 150

Answers (2)

Vahid
Vahid

Reputation: 136

Your server class must use multiple threads to handle all connections:

class MyServer {


    private ServerSocket servsock;

    MyServer(){
        servsock = new ServerSocket(PORT_NUMBER);
    }

    public void waitForConnection(){
        while(true){
            Socket socket = servsock.accept();
            doService(socket);
        }
    }

    private void doService(Socket socket){
        Thread t = new Thread(new Runnable(){
            public void run(){
                while(!socket.isClosed()){
                    Scanner in = new Scanner(sock.getInputStream());
                    PrintWriter out = new PrintWriter(sock.getOutputStream());
                    String request = "";
                    // and write your code
                }
            }
        });
        t.start();
    }
}

Upvotes: 1

sasbury
sasbury

Reputation: 301

Multi-client servers are generally written one of two ways:

  1. Create a thread for each client. To do this you would create a thread to handle the calls to accept() on the server socket and then spawn a new thread to handle calls on the Socket that it returns. If you do this, you need to make sure you isolate the code for each socket as much as possible. The accept thread will loop forever, or until a flag is set, and will just call accept, spawn a thread with the new socket, and go back to calling accept. All of the work is in the child thread.

  2. Use NIO, or another technology, to multi-plex work into 1 more more threads. NIO uses a concept sometimes called select, where your code will be called when there is input available from a specific socket.

If you are just doing a small server, you can go with the simplest design and also won't have too many clients, so I would go with #1. If you are doing a big production server, I would look into a framework like netty or jetty that will help you do #2. NIO can be tricky.

In either case, be very careful with threads and the file system, you might not get the results you expect if you don't use a Lock from the concurrency package, or synchronize, or another locking scheme.

My final advice, be careful with having a client tell a server to do anything with the file system. Just saying, that is a dangerous thing to do ;-)

Upvotes: 2

Related Questions