Home

Forums

Web development

 

 

 

 
     
 
dna88 Web development and Technology Forum
 
Profile   Register   Memberlist   Usergroups   FAQ   Search  Log in
How to allow limited users in this server program?

 
Post new topic   Reply to topic    dna88 Forum Index -> Programming in Java, C, C#, VB, .NET Discussion Forum
Author Message
tanveer
User
User


Joined: 21 Jun 2004
Posts: 85
Location: Dhaka,Bangladesh

Post Post subject: How to allow limited users in this server program? Reply with quote

hello friends,
Here is a simple threaded server program using UDP protocol.
Now I am wanting it to serve no more than 5 user at a time and if 6th user hits in then it will show a message like " Stack Is Full, Try later".
It has 3 part: a)NetServer.java b)NetServerThr.java c)UDPClient.java

NetServer.java code :-
class NetServer {
public static void main(String[] args) {
// NetServerThr thr[]=new NetServerThr[5];
// for(int i=0;i<5;i++)
new NetServerThr().start();
// thr[i].start();
}
}

NetServerThr.java Code:-
import java.io.*;
import java.net.*;
import java.util.*;

class NetServerThr extends Thread {
private DatagramSocket socket = null;

NetServerThr()
{
super("NetServer");
try {
socket = new DatagramSocket(6789);

} catch (java.net.SocketException e)
{
System.err.println("Could not create datagram socket.");
}
}

public void run() {
int i = 0;

if (socket == null)
return;

while (true) {
try {
byte[] receiveData = new byte[256];
byte[] sendData = new byte[1024];

DatagramPacket receivePacket,sendPacket;
InetAddress address;
int port;
String dString = null;

// receive request
receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
dString=new String(receivePacket.getData());
//System.out.print("Message:"+dString);
address = receivePacket.getAddress();
port = receivePacket.getPort();

String capitalizedSentence=dString.toUpperCase();
sendData=capitalizedSentence.getBytes();

// System.out.print("Message:"+capitalizedSentence);
// send response
i = i + 1;
System.out.println("Client Request # "+i+" "+address+" "+port);
if(i==5)
System.out.println("\t STACK FULL !!! IGNORING REQUEST !!! ");
receiveData[0] = (byte)i;
// sendPacket = new DatagramPacket(buf, 1, address, port);
sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
socket.send(sendPacket);

} catch (Exception e) {

System.err.println("Exception: " + e);
e.printStackTrace();
}
}
}
protected void finalize() {
if (socket != null) {
socket.close();
socket = null;
System.out.println("Closing datagram socket.");
}
}

}
UDPCleint.java Code :-
import java.io.*;
import java.net.*;

class UDPClient
{
public static void main(String argv[]) throws Exception
{

BufferedReader inFromUser=
new BufferedReader(new InputStreamReader(System.in));

DatagramSocket clientSocket= new DatagramSocket();

InetAddress IPAddress=InetAddress.getLocalHost();
//.getByName(String hostname); "CL11"

System.out.println(IPAddress);

byte [] sendData=new byte[1024];
byte [] receiveData=new byte[1024];

String sentence=inFromUser.readLine();

sendData=sentence.getBytes();

DatagramPacket sendPacket=
new DatagramPacket(sendData,sendData.length,IPAddress,6789);

clientSocket.send(sendPacket);

DatagramPacket receivePacket=
new DatagramPacket(receiveData,receiveData.length);

clientSocket.receive(receivePacket);

String modifiedSentence=
new String(receivePacket.getData());
System.out.println("From Server: "+modifiedSentence);
clientSocket.close();

}
}
Tue Jun 29, 04 8:48 am
Back to top
tanveer View user's profile Send private message
Belal
User
User


Joined: 08 Mar 2004
Posts: 84
Location: Dhaka, Bangladesh

Post Post subject: limiting user java server Reply with quote

mr. tanveer,
i've seen ur code. can u please explain what this code is exactly doing?
i haven't found any relationship btn client and server code. I think u
should first make it work. just try to make a client that request to server.
if u can make it, i think the rest of work is easy. if ur server is working then
instead of counting client in ur thread, do it in the main server.java program.

//NetServerThr.java
//if(i==5)
//System.out.println("\t STACK FULL !!! IGNORING REQUEST !!! ");

in this section u r printing message in server side. u should send the message to
the client who is trying to connect.

if u r not being able to connect client and server, then let me know. i will try
to help u with some code after my return from vacation.

thank u

[tcp/ip has surver_socket constructor like ServerSocket(int port,int maxQueue) which
does the same work. if u don't have any special reason for using datagram socket
u can use tcp/ip server socket, it will b easy]
_________________
we've lot of things to think abt curr probs
so, i don't have time to think abt religion or wonder of sceice .......... how ppl can waste their time like this?
Wed Jun 30, 04 2:19 am
Back to top
Belal View user's profile Send private message Yahoo Messenger MSN Messenger
tanveer
User
User


Joined: 21 Jun 2004
Posts: 85
Location: Dhaka,Bangladesh

Post Post subject: Re: How to allow limited users in this server program? Reply with quote

First thanz for ur reply Mr. Belal.
What i am trying to do here is to allow not more than 5 users to put request in the server all in parallel. If #6 user knocked at that time while server is serving the other 5 clients request then it will show the 6th user a message.
I have to do it in UDP and I also have done the normal client-server request program using TCP/IP and UDP protocol.
In those 3 programs i submitted first compile all of them then run NetServer.java which will start the server and will b waiting for requests from clients. Now run the UDPClient.java and write something which will b sent to server and will b returned to that client in uppercase.
I know how to write back to client but my problem is how to make the serverpart threaded so that it can service multple clients at a time and also ! more than 5 user and that's why i added the counter.
Sample input and output after running UDPClient.java:-
[root @localhost bin#] java UDPClient
localhost.localdomain /127.0.0.1
Hello
From Server: HELLO
Sample input and output after running NetServer.java:-
Client Request #1 /127.0.0.1 : 32799
Client Request #2 /127.0.0.1 : 32799
and will go on like this until i==5 and then it will print the msg.
A very big history.
Hope I made myself clear and have a graet vacation.
Wed Jun 30, 04 12:30 pm
Back to top
tanveer View user's profile Send private message
Tousif
Beginner User
Beginner User


Joined: 25 May 2004
Posts: 20
Location: Nashville, Tennessee, USA

Post Post subject: Reply with quote

Hi,
When multiple processes are accessing parallely, you need to protect your critical section by using a SEMAPHORE. If I am not mistaken, all those thread, when you start them -executes the run program parallely. So everytime a client makes a request, you increase the same "i", and then compare to see if it is equal to 5 -if so print error.
Since all the processes could be incrementing the variable i and accessing it at the same time, you want to make it global and use a global semaphore wraped around that incrementing and compare statement to make sure that only one process can modify i and compare the value of it at any given time.
I hope I was able to explain it clearly.

Tousif
Thu Jul 01, 04 1:38 am
Back to top
Tousif View user's profile Send private message
tanveer
User
User


Joined: 21 Jun 2004
Posts: 85
Location: Dhaka,Bangladesh

Post Post subject: Reply with quote

back again.
I am given a new program which is threaded and allow multiople client requests. now what I have to do with this is I have to maintain an array of size 5 and check it each time before a new thread starts because I have to put an entry in that array like '1' means for every incoming requests i have to put a value in that array if any of its fields are empty.
Suppose first request came and I put 1 in arr[0]. second requerst came and put 1 in arr[1]. now when third request came in and thread one done processing then put 1 in arr[0] not in arr[2].
Now where to put that array and how to know if any particular thread ended? Where to use isAlive() function?

Hope I made myself clear.

Code:

import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

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

class ClientWorker implements Runnable {
  private Socket client;
  private JTextArea textArea;
 
  ClientWorker(Socket client, JTextArea textArea) {
   this.client = client;
   this.textArea = textArea;   
  }

  public void run(){
    String line;
    BufferedReader in = null;
    PrintWriter out = null;
    try{
      in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
      System.out.println("in or out failed");
      System.exit(-1);
    }

    while(true){
      try{
        line = in.readLine();
//Send data back to client
         out.println(line);
         textArea.append(line);
       } catch (IOException e) {
         System.out.println("Read failed");
         System.exit(-1);
       }
    }
  }
}

class SocketThrdServer extends JFrame{

   JLabel label = new JLabel("Text received over socket:");
   JPanel panel;
   JTextArea textArea = new JTextArea();
   ServerSocket server = null;

   SocketThrdServer(){ //Begin Constructor
     panel = new JPanel();
     panel.setLayout(new BorderLayout());
     panel.setBackground(Color.white);
     getContentPane().add(panel);
     panel.add("North", label);
     panel.add("Center", textArea);
   } //End Constructor

  public void listenSocket(){
    try{
      server = new ServerSocket(4444);
    } catch (IOException e) {
      System.out.println("Could not listen on port 4444");
      System.exit(-1);
    }
    while(true){
      ClientWorker w;
      try{
        w = new ClientWorker(server.accept(), textArea);
        Thread t = new Thread(w);
        t.start();
      } catch (IOException e) {
        System.out.println("Accept failed: 4444");
        System.exit(-1);
      }
    }
  }

  protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
     try{
        server.close();
    } catch (IOException e) {
        System.out.println("Could not close socket");
        System.exit(-1);
    }
  }

  public static void main(String[] args){
        SocketThrdServer frame = new SocketThrdServer();
   frame.setTitle("Server Program");
        WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                        System.exit(0);
                }
        };
        frame.addWindowListener(l);
        frame.pack();
        frame.setVisible(true);
        frame.listenSocket();
  }
}

client code :-
Code:

import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

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

class SocketClient extends JFrame
       implements ActionListener {

   JLabel text, clicked;
   JButton button;
   JPanel panel;
   JTextField textField;
   Socket socket = null;
   PrintWriter out = null;
   BufferedReader in = null;

   SocketClient(){ //Begin Constructor
     text = new JLabel("Text to send over socket:");
     textField = new JTextField(20);
     button = new JButton("Click Me");
     button.addActionListener(this);

     panel = new JPanel();
     panel.setLayout(new BorderLayout());
     panel.setBackground(Color.white);
     getContentPane().add(panel);
     panel.add("North", text);
     panel.add("Center", textField);
     panel.add("South", button);
   } //End Constructor

  public void actionPerformed(ActionEvent event){
     Object source = event.getSource();

     if(source == button){
//Send data over socket
          String text = textField.getText();
          out.println(text);
     textField.setText(new String(""));
//Receive text from server
       try{
     String line = in.readLine();
          System.out.println("Text received :" + line);
       } catch (IOException e){
    System.out.println("Read failed");
           System.exit(1);
       }
     }
  }
 
  public void listenSocket(){
//Create socket connection
     try{
       socket = new Socket("localhost", 4444);
       out = new PrintWriter(socket.getOutputStream(), true);
       in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     } catch (UnknownHostException e) {
       System.out.println("Unknown host: localhost:127.0.0.1");
       System.exit(1);
     } catch  (IOException e) {
       System.out.println("No I/O");
       System.exit(1);
     }
  }

   public static void main(String[] args){
        SocketClient frame = new SocketClient();
   frame.setTitle("Client Program");
        WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                        System.exit(0);
                }
        };

        frame.addWindowListener(l);
        frame.pack();
        frame.setVisible(true);
   frame.listenSocket();
  }
}
Fri Jul 23, 04 8:52 pm
Back to top
tanveer View user's profile Send private message
Tousif
Beginner User
Beginner User


Joined: 25 May 2004
Posts: 20
Location: Nashville, Tennessee, USA

Post Post subject: Reply with quote

Hi,
First of all I would like to make it a point that none of the people here are just waiting for a problem to be posted and get busy solving it...So, the expectation that one could just throw in a problem (an education related problem as in this case it looks like), with a COMMANDING tone to get a solution without any regard to its audience should be utterly discouraged.
I could not help but writing this because I feel that a little bit of courtesy, appreciation and FOLLOW UPs to previous problems should be accompanied by your post before throwing in bunch of codes. We are here to help each other and if we just remember these little things, it makes things much more enjoyable.
As far as the problem is concerned, you could keep track when a thread ends in the "finalize" method. Concerning array, if that is what you would like to implement, why not use a linked like? This would be much easier and simpler.

Hope this Helps. If you need more explanation, just write back, I would be able to help you after thursday.

Best,
Tousif
Sat Jul 24, 04 11:54 am
Back to top
Tousif View user's profile Send private message
tanveer
User
User


Joined: 21 Jun 2004
Posts: 85
Location: Dhaka,Bangladesh

Post Post subject: Reply with quote

First of all I apologize to u all for my bad manner/attitude and u r correct, a friend of mine had stuck in this class project and told me to solve this while I was busy with my online project thats why I posted it here so that U great guyz can solve this in a second which will take a lot of time for me.
Morevover, if u read me earlier posts then u can see I thanked Belal for his help before.
Sorry once again If i hurt ur feelings.
By the way I solved it. THANZ A LOT.
Sat Jul 24, 04 12:14 pm
Back to top
tanveer View user's profile Send private message
Tousif
Beginner User
Beginner User


Joined: 25 May 2004
Posts: 20
Location: Nashville, Tennessee, USA

Post Post subject: Reply with quote

Thats so nice of you....great to hear that you've solved it.

Thanks a bunch

Cheers,
Tousif
Thu Jul 29, 04 6:00 am
Back to top
Tousif View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    dna88 Forum Index -> Programming in Java, C, C#, VB, .NET Discussion Forum All times are GMT - 7 Hours
Page 1 of 1

 

Partners and Resources

Bangladesh hosting company

Bangladesh web design

Driven by phpBB © phpBB Group