Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Socket programming something gone wrong

  1. #1
    Junior Member
    Join Date
    Mar 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Socket programming something gone wrong

    Hi All,

    I have this code in which i am attempting to broadcast messages to all clients connected.Currently i have a server and can support upto max of 10 clients.
    When a client1 sends a message , the server intercepts it and sends an ACK to the calling client.Until the client recieves an ACK i want to stop this client from sending further messages.
    On the server, once i send teh ACk to CLient1 i want to broadcast this msg to the n clients connected.
    Currently i see that after 3 runs my code hangs on client and whatever msg i send from client is nvr getting printed.
    If i run using a debugger on server i am able to get this working.Guess the issue is with threads.
    Please help.

    ----------------------------------------------------------------------------
    SERVER CODE
    ----------------------------------------------------------------------------
    import java.io.*;
    import java.lang.management.ThreadInfo;
    import java.net.*;
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.BlockingQueue;
     
    public class MultiThreadChatServer{
     
        // Declaration section:
        // declare a server socket and a client socket for the server
        // declare an input and an output stream
     
        static  Socket clientSocket = null;
        static  ServerSocket serverSocket = null;
     
        // This chat server can accept up to 10 clients' connections
        static  clientThread t[] = new clientThread[10];           
     
        public static void main(String args[]) {
     
    	// The default port
     
    	int port_number=2229;
     
     
    	// Initialization section:
    	// Try to open a server socket on port port_number (default 2222)
    	// Note that we can't choose a port less than 1023 if we are not
    	// privileged users (root)
     
            try {
    	    serverSocket = new ServerSocket(port_number);
            }
            catch (IOException e)
    	    {System.out.println(e);}
     
    	// Create a socket object from the ServerSocket to listen and accept 
    	// connections.
    	// Open input and output streams for this socket will be created in 
    	// client's thread since every client is served by the server in
    	// an individual thread
     
    	while(true){
    	    try {
    		clientSocket = serverSocket.accept();
    		for(int i=0; i<=9; i++){
    		    if(t[i]==null)
    			{
    			    (t[i] = new clientThread(clientSocket,t)).start();
    			    break;
    			}
    		}
    	    }
    	    catch (IOException e) {
    		System.out.println(e);}
    	}
        }
    } 
     
    // This client thread opens the input and the output streams for a particular client,
    // ask the client's name, informs all the clients currently connected to the 
    // server about the fact that a new client has joined the chat room, 
    // and as long as it receive data, echos that data back to all other clients.
    // When the client leaves the chat room this thread informs also all the
    // clients about that and terminates. 
     
    class clientThread extends Thread{
     
        DataInputStream is = null;
        PrintStream os = null;
        Socket clientSocket = null;       
        clientThread t[]; 
     
        public clientThread(Socket clientSocket, clientThread[] t){
    	this.clientSocket=clientSocket;
            this.t=t;
        }
     
        public void run() 
        {
    	String line;
            String name;
            BlockingQueue<String> queue =new ArrayBlockingQueue<String>(200);
    	try{
    	    is = new DataInputStream(clientSocket.getInputStream());
    	    os = new PrintStream(clientSocket.getOutputStream());
     
    	    os.println("Enter your name.");
    	    name = is.readLine();
    	    t[0].os.println("ACK");
    	    for(int i=0; i<=9; i++)
    		if (t[i]!=null && t[i]==this)  
    		    System.out.println("*** A new user "+name+" entered the service !!! ***" );
    	    while (true) {
    		line = is.readLine();
    		try{
    			if(line.startsWith("quit")) break; 
    			queue.put(line);
    			for(int i=0; i<=9; i++)
    			    if (t[i]!=null && t[i]==this) {
    			    	t[i].os.println("ACK");
    			    }
     
     
     
                    String item=null;
    		for(int i=0; i<=9; i++)
    		    if (t[i]!=null) {
    		    	if(i==0)
    		    		item=queue.take();
    		    	t[i].os.println("<"+name+"> "+item); 
    		    }
    		}catch(InterruptedException w)
    		{
    			System.out.println("Interrupt");
    		}
    	    }
    	    for(int i=0; i<=9; i++)
    		if (t[i]!=null && t[i]!=this)  
    		    System.out.println("*** The client "+name+" is leaving the service !!! ***" );
     
    	    os.println("*** Bye "+name+" ***"); 
     
    	    // Clean up:
    	    // Set to null the current thread variable such that other client could
    	    // be accepted by the server
     
    	    for(int i=0; i<=9; i++)
    		if (t[i]==this) t[i]=null;  
     
    	    // close the output stream
    	    // close the input stream
    	    // close the socket
     
    	    is.close();
    	    os.close();
    	    clientSocket.close();
    	}
    	catch(IOException e){};
        }
    }

    ----------------------------------------------------------
    CLIENT
    ----------------------------------------------------------

    import java.io.*;
    import java.lang.management.ManagementFactory;
    import java.net.*;
     
    public class MultiThreadChatClient implements Runnable{
     
        // Declaration section
        // clientClient: the client socket
        // os: the output stream
        // is: the input stream
     
        static Socket clientSocket = null;
        static PrintStream os = null;
        static DataInputStream is = null;
        static BufferedReader inputLine = null;
        static boolean closed = false;
        static boolean blocked = false;
        static int seqNo=0;
     
        public static void main(String[] args) {
     
    	// The default port	
     
    	int port_number=2229;
            String host="localhost";
     
    	// Initialization section:
    	// Try to open a socket on a given host and port
    	// Try to open input and output streams
    	try {
                clientSocket = new Socket(host, port_number);
                inputLine = new BufferedReader(new InputStreamReader(System.in));
                os = new PrintStream(clientSocket.getOutputStream());
                is = new DataInputStream(clientSocket.getInputStream());
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host "+host);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to the host "+host);
            }
     
    	// If everything has been initialized then we want to write some data
    	// to the socket we have opened a connection to on port port_number 
     
            if (clientSocket != null && os != null && is != null) {
                try {
     
    		// Create a thread to read from the server
     
                    new Thread(new MultiThreadChatClient()).start();
     
    		while (!closed ) {
    				if(!blocked){
     
                        os.println(inputLine.readLine()+"^^"+ManagementFactory.getRuntimeMXBean().getName().split("@")[0]+"^^"+seqNo);
                        System.out.println("I AM HERE");
                        blocked=true;
                        seqNo++;
    				}
     
                    }
     
    		// Clean up:
    		// close the output stream
    		// close the input stream
    		// close the socket
     
    		os.close();
    		is.close();
    		clientSocket.close();   
                } catch (IOException e) {
                    System.err.println("IOException:  " + e);
                }
            }
        }           
     
        public void run() {		
    	String responseLine;
     
    	// Keep on reading from the socket till we receive the "Bye" from the server,
    	// once we received that then we want to break.
    	try{ 
    	    while ((responseLine = is.readLine()) != null) {
    	    	if(responseLine.equals("ACK")){
    	    		blocked=false;
    	    	}
    	    	//System.out.println("blocked:"+blocked);
    		System.out.println(responseLine);
     
    		if (responseLine.indexOf("*** Bye") != -1) break;
    	    }
                closed=true;
    	} catch (IOException e) {
    	    System.err.println("IOException:  " + e);
    	}
        }
    }
    Last edited by copeg; March 6th, 2011 at 10:45 AM.


  2. #2
    Super Moderator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,099
    Thanks
    169
    Thanked 779 Times in 725 Posts
    Blog Entries
    5

    Default Re: Socket programming something gone wrong

    Move to Java Networking

    For future reference, please flank your code with the [highlight=java][/highlight] tags. Makes the code much more readable (I've edited your post to reflect this)

Similar Threads

  1. [SOLVED] Socket Programming Problem
    By relixus in forum What's Wrong With My Code?
    Replies: 7
    Last Post: December 9th, 2010, 09:35 PM
  2. Socket C
    By ighor10 in forum Java Networking
    Replies: 0
    Last Post: June 22nd, 2010, 06:56 AM
  3. Java socket programming
    By lucy in forum Java Networking
    Replies: 1
    Last Post: April 26th, 2010, 09:13 PM
  4. Access the Same Socket
    By ahmmnhwa in forum Java Networking
    Replies: 5
    Last Post: October 29th, 2009, 11:50 AM
  5. need multithread socket ??
    By cilang in forum Java Theory & Questions
    Replies: 1
    Last Post: September 1st, 2009, 05:14 AM

Tags for this Thread