Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 2 of 2 FirstFirst 12
Results 16 to 22 of 22
  1. #16
    New Coder
    Join Date
    Aug 2002
    Posts
    73
    Thanks
    0
    Thanked 0 Times in 0 Posts
    It's new code that I'll be able to use for future client/server projects. One of my goals is to build an http proxy/cache server and this is some of the groundwork.

  2. #17
    Senior Coder
    Join Date
    Apr 2003
    Location
    England
    Posts
    1,192
    Thanks
    5
    Thanked 13 Times in 13 Posts
    argh, as i probably shouldnt just use yours, i continued making my own (although yours was useful )

    but the guy on the sun forum helped me right up to the point of my original question and refuses to help me with that ¬_¬.. i hate that forum

    heres my non-working code so far, i cant find my last working code but im just a little stuck with making it so that if any user types the kill server command (/kill) it shuts down the server (synchronised variables or something) and how to loop it so that more than one user can connect at once

    i put //--------------- around the broken code and he wouldnt tell me what to put where // ... is out of my original code

    on a sidenote: for some reason if someone sets up a socket to the server on the client side without doing anything else, it crashes the server, but id like to get multiple users able to connect before i look into this

    Code:
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.io.PrintWriter;
    import java.net.BindException;
    import java.net.SocketException;
    import java.net.ServerSocket;
    import java.net.Socket;
     
    public class Server
    {
    	public static void main(String args[])
    	{
    		Server server = new Server(9001);
    		server.execute();
    	}
    	
    	//----------------------
    	private boolean blnKeepAlive = true;
    	protected synchornized boolean isKeepAlive()
    	{
    		return blnKeepAlive;
    	}
    	
    	protected synchronized void setKeepAlive(boolean blnKeepAlive)
    	{
    		this.blnKeepAlive = blnKeepAlive;
    	}
    	
    	public void execute()
    	{
    		// ...
    		// Inside your method, where you loop the server accepting
    		while( isKeepAlive() )
    		{ 
    			// ...
    			// Store the created threads, so you can stop them afterwards
    			list.add(echoThread);
    		}
    		
    		// Before you close your server, you must allow every thread to stop graciously
    		for (Iterator iter = list.iterator(); iter.hasNext();)
    		{
    			Thread echoerThread = (Thread) iter.next();
    			try
    			{
    				echoerThread.interrupt();
    				echoerThread.join(5000);
    			}
    			catch (InterruptedException e)
    			{
    				e.printStackTrace();
    			}
    		}
    	}
    	//----------------------
    	
    	public Server(int intPort)
    	{
    		//int intPort = 9001;
    		
    		ServerSocket		objServerSocket;
    		Socket			objSocket;
    		
    		try
    		{
    			//---Start listening on port---
    			objServerSocket = new ServerSocket(intPort);
    			
    			objSocket = objServerSocket.accept();
    			
    			//---Make a new thread for each connection---
    			Thread echoThread = new Thread(new Echoer(objSocket));
    			echoThread.start();
    			
    			//---Clean Up---
    			objServerSocket.close();
    		}
    		catch(BindException be)
    		{
    			System.out.println("BindException: \n\t" + "Port " + intPort + " already in use");
    		}
    		catch(SocketException se)
    		{
    			System.out.println("SocketException: Client has disconnected");
    		}
    		catch(Exception e)
    		{
    			System.out.println("Exception: \n\t" + e);
    		}
    	}
    	
    	private class Echoer implements Runnable
    	{
    		String data;
    		
    		BufferedReader		objInBuffer;
    		PrintWriter		objOutStream;
    		
    		public Echoer(Socket objSocket)
    		{
    			try
    			{
    				//---Set up streams---
    				this.objInBuffer = new BufferedReader(new InputStreamReader(objSocket.getInputStream()));
    				this.objOutStream = new PrintWriter(objSocket.getOutputStream(), true);
    			}
    			catch(IOException ioe)
    			{
    				System.out.println("IOException:\n\t" + ioe);
    			}
    		}
    		
    		public void run()
    		{
    			System.out.println("Client has connected to server!");
    			
    			//---Receive Data---
    			while(true)
    			{
    				try
    				{
    				    data = objInBuffer.readLine();
    				}
    				catch(IOException ioe)
    				{
    					System.out.println("IOException:\n\t" + ioe);
    					System.exit(0);
    				}
    				
    				if(data.startsWith("/"))
    				{
    					//---Respond to Command---
    					if(data.toLowerCase().equals("/kill"))
    					{
    						objOutStream.println("*KILLING SERVER*");
    						objOutStream.flush();
    						setKeepAlive(false)
    						break;
    					}
    				}
    				else
    				{
    					//---Echo clients data back---
    					System.out.println("Echoing string: '" + data + "'");
    					objOutStream.println(data);
    					objOutStream.flush();
    				}
    			}
    			
    			//---Clean Up---
    			try
    			{
    			    objOutStream.close();
    			    objInBuffer.close();
    			}
    			catch(IOException ioe)
    			{
    				System.out.println("IOException:\n\t" + ioe);
    			}
    		}
    	}
    }

  3. #18
    JPM
    JPM is offline
    Regular Coder
    Join Date
    Mar 2004
    Location
    Norway
    Posts
    204
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Dont know if it will be to any help but here's a sever I made some days ago. When someone writes something the server echos it out to all who are logged on . (>>NameHere: message).

    Its just a regular 'echo server' only it has an array with all the socket objects. So when someone says something the method printAll is called, and it gets the socket array 'Multi.allConnected[i].....println();' (unless the user writes a command such as 'users')

    There is also a mehtod that removes someone from the array, in the final statement of the run method.

    edit:just noticed that some variable names and output text is in norvegian...also if some of you try it out please let me know if you find any bugs...

    For a client you can use Telnet.

    Code:
    import java.io.*;
    import java.net.*;
    import java.util.Vector;
    
     class Server extends Thread
     {
    
    
            String linje;
            BufferedReader input;
            PrintWriter output;
            Socket socket = null;
            String navn;
            boolean exit = false;
    
            public Server(Socket s) throws IOException
            {
    			socket = s;
    			input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    			output = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
    
    			start();
    		}
    
    		public void run()
    		{
    
    			System.out.println("Klient logget på");
    			output.println(">>Velkommen!");
    			output.println(">>Brukernavn: ");
    			try
    			{
    				navn = input.readLine();
    				for(int i=0; i<Multi.allN.length; i++)
    				{
    					if(Multi.allN[i] == null)
    					{
    						Multi.allN[i] = navn;
    					    break;
    					}
    				}
    
    				for(int i=0;i<Multi.allConnected.length; i++)
    				{
    					if(Multi.allConnected[i] == null)
    					{
    						Multi.allConnected[i] = socket;
    						break;
    					}
    			    }
    
    			}
    			catch(IOException e) { System.out.println(e); }
    			output.println(">> **********  DU ER LOGGET INN  **********");
    			output.println(">> ");
    
    
    			try
    			{
    				String lg =">> " + navn + " har logget inn";
    				printAll(lg,"");
    				while((linje = input.readLine()) != null && exit==false)
    				{
    					System.out.println(linje);
    					printAll(linje,navn);
    
    				}
    			}
    			catch(IOException e) { e.printStackTrace(); }
    
    			finally
    			{
    				try
    				{
    					System.out.println("Klient logget av");
                        remove(socket,navn);
    				    input.close();
    				    output.close();
    				    socket.close();
    			    }
    			    catch(IOException e) { System.out.println(e); }
    			}
    		}
    
    		void printAll(String linje,String navn) throws IOException
    		{
    			String[] commands = new String[3];
    			         commands[0] = "help";
    			         commands[1] = "exit";
    			         commands[2] = "users";
    			for(int i=0; i<commands.length; i++)
    			{
    				if(linje.equalsIgnoreCase(commands[i])) { doCommand(i); return; }
    			}
    			PrintWriter writer;
    			int i = 0;
    			while(Multi.allConnected[i] != null)
    			{
    				Socket current = (Socket) Multi.allConnected[i];
    				writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(current.getOutputStream())),true);
    				writer.println(navn+": "+linje);
    				i++;
    			}
    
    		}
    		void remove(Socket socket, String name)
    		{
    			for(int i=0; i<Multi.allConnected.length; i++)
    			{
    				if(socket.equals(Multi.allConnected[i]))
    				{
    					Multi.allConnected[i] = null;
    					break;
    				}
    			}
    
    			for(int i=0; i<Multi.allN.length; i++)
    			{
    				if(name.equals(Multi.allN[i]))
    				{
    					Multi.allN[i] = null;
    					break;
    				}
    			}
    		}
    
    		void doCommand(int com)
    		{
    			switch(com)
    			{
    				case 0: output.println(">> help, exit, users"); break;
    				case 1: exit=true; output.println("Du er logget av. Trykk en tast"); break;
    				case 2: output.println("Brukere:");
    				        for(int i=0; i<Multi.allN.length; i++)
    				        {
    							if(Multi.allN[i] != null) output.println(Multi.allN[i]);
    							else break;
    						}
    			}
    		}
    
    
     }
    
    
    
     public class Multi
     {
    	 static Socket[] allConnected = new Socket[100];
    	 static String[] allN = new String[100];
    
    	 public static void main(String[] args) throws IOException
    	 {
    	     ServerSocket sS = new ServerSocket(1250);
    	     System.out.println("Venter....");
    	     try
    	     {
    
    	         while(true)
    	         {
    		    	 Socket s = sS.accept();
    		    	 try
    		    	 {
    		    		 new Server(s); // start a new server thread
    		    	 }
    		    	 catch(IOException e) { s.close(); System.out.println(e); }
    		     }
    		 }
    		 finally
    		 {
    			 sS.close();
    		 }
    	 }
     }
    Last edited by JPM; 01-12-2005 at 04:32 PM.
    <JPM />

  4. #19
    Senior Coder
    Join Date
    Apr 2003
    Location
    England
    Posts
    1,192
    Thanks
    5
    Thanked 13 Times in 13 Posts
    i think i pretty much got that all into english, adding some things like channels and more functions etc (eventually it will have functionality similar to irc, shudnt be too hard)

    thanks, it works great

    however, im not sure about this (i corrected it in mine just incase):
    if a user logs out, eg u have this in the array of names
    "guest0", null, "guest2"
    will it send messages to guest2 or anyone after this at all as it has a while not null

    i was thinking of when someone logs out set their name to "" instead of null and then all the loops check it isnt "" then stop at the first null, this should allow it to only loop untill the final user without cutting out half way right?

    i havnt done this yet, i just loop though all the nulls and put an if not null in it, but if i put the max users to 10,000 it would loop 10k times for several sections of code (not do anything, just loop 10k times and check against null, then do something if not null) even though there is nothing left to loop though after a few users

    im just not sure on the best course of action

    also i made a client but its pants, it uses 1 thread for incomming and one for outgoing messages, am i missing any threads or anything?

    EDIT: also i will need to make a database to store registered usernames and channels, what is a good type of database to do this with and how can i use it? in a prievious project i use a simple text file but this isnt really the best way of doing it as far as i can see
    Last edited by ghell; 02-01-2005 at 04:53 PM.

  5. #20
    New to the CF scene
    Join Date
    Oct 2009
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    maa ka

    you guys cant give me a client to client connection code....JHATA TUM LOGON KA!! LKB!

  6. #21
    New to the CF scene
    Join Date
    Oct 2009
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    _|_

    _|_ to every1

  7. #22
    New to the CF scene
    Join Date
    Oct 2009
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    ghell you suck! rynox u tho dont have any brains...i have more brains!


 
Page 2 of 2 FirstFirst 12

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •