I'm trying to do some socket programming in java. what i have is, i've written this program to create a server and client on my local machine and make separate two threads for socket input and out put in Se.java file. Similarly two separate threads for socket input and output at client side in file Cl.java

Now, when i compile both of them they show no errors or exceptions but when i run it, the server with some exception continues but client crashes

i dont know what seems to be wrong.all i want to do is create two threads for each,server and client, that keep check of reading and writing to sockets respectively.any suggestion for it would be a great help

PS. sorry if the question is too "noobie-ish".please be easy on me.this is my first post here

this same program,at prior worked perfectly,when i had just one thread in each of the client file Cl.java to read input from server and print it, and one in server side to read input from client and print it. but the problem came when i made two threads in each of the server and client program for reading and writing strings.

any suggestion would be welcomed.just wanted to make two separate threads at client side and server side for reading and writing.

here is my full code for Server:

Se.java

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

public class Se
{
    public static int i=0;

    public static BufferedReader stdIn =null;

    public static void main (String [] args) throws IOException
    {
        ServerSocket serverSocket = null ;

        try {
            serverSocket = new ServerSocket (4321);
        }
        catch (IOException e)
        {
            System.err.println("Could not listen to the server port.");
            System.exit (1);
        }

        Socket clientSocket= null;

        try{
            clientSocket= serverSocket.accept();

            new Thread(new Sconsole(clientSocket));
            new Thread(new Slistener(clientSocket));

        }
        catch(Exception e)
        {
            System.err.println("Accept failed");
            System.exit(1);
        }

        stdIn.close();
        clientSocket.close();
        serverSocket.close();
    }
}


/* thread to listen from client and print it at server console */
class Slistener implements Runnable
{
    Socket channel=null;
    public static PrintWriter out = null;
    public static BufferedReader in = null;
    public static String inputL=null;
    public static boolean closed=true;

    public Slistener(Socket Soc)
    {
        this.channel=Soc;

        try
        {
            in=new BufferedReader(new InputStreamReader(channel.getInputStream()));
            //closed=false;

            new Thread(new Slistener(channel)).start();
        }
        catch(IOException e)
        {
            System.out.println("error in making stream from server to client");
        }

    }
    public void run ()
    {
        try
        {
            while((inputL=in.readLine())!= null)
            {
                System.out.println("SERVER:" + inputL);

                if (inputL.equals ("Bye.")) break;
            }

        }
        catch (IOException e)
        {
            System.out.println("Exception thrown at run loop.");
        }
    }
}



/* thread to listen from console at server end and print it at client console */
class Sconsole implements Runnable
{
    Socket channel=null;
    public static PrintWriter out = null;
    public static BufferedReader in = null;
    public static String inputL=null;
    //public static boolean closed=true;

    public Sconsole() {}

    public Sconsole(Socket Soc)
    {
        this.channel=Soc;

        try
        {
            out=new PrintWriter(channel.getOutputStream(), true);
            in=new BufferedReader(new InputStreamReader(System.in));

            //closed=false;

            new Thread(new Sconsole(channel)).start(); // at this line the program hangs up as soon as i run it
        }
        catch(Exception e)
        {
            System.out.println("error in writing to stream from server to client");
        }

    }
    public void run ()
    {
        try
        {
            System.out.println("SERVER:");

            while(true)
            {
                inputL=in.readLine();

                out.println(inputL);

                if (inputL.equals ("End.")) break;
            }
            //closed=true;

        }
        catch (Exception e)
        {
            System.out.println("Exception thrown at run loop.");
        }
    }
}

Now Client code:

Cl.java

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

public class Cl extends Thread
{
    public static Socket channel= null;

    public static void main(String args[]) throws IOException
    {
        try{
            channel= new Socket ("localhost", 4321);

            System.out.println("client connected");

            new Thread(new Clistener(channel));
            new Thread(new Cconsole(channel));

        }
        catch (Exception e)
        {
            System.err.println("Unknown Exception");
            System.exit(1);
        }

        channel.close();
    }           
}


  /* thread to listen from server and print it at client console */
class Clistener implements Runnable
{
    Socket channel=null;
    public static PrintWriter out = null;
    public static BufferedReader in = null;
    public static String inputL=null;

    public Clistener() {}

    public Clistener(Socket Soc)
    {
        this.channel=Soc;

        try
        {
            in=new BufferedReader(new InputStreamReader(channel.getInputStream()));

            new Thread(new Clistener(channel)).start();
        }
        catch(IOException e)
        {
            System.out.println("error in making stream from server to client");
        }

    }
    public void run ()
    {
        try
        {
            while(true)
            {
                inputL=in.readLine();

                System.out.println("SERVER:" + inputL);

                if (inputL.equals ("Bye.")) break;
            }



        }
        catch (IOException e)
        {
            System.out.println("Exception thrown at run loop.");
        }
    }
}

  /* thread to listen from client console and print it at server console */
class Cconsole implements Runnable
{
    Socket channel=null;
    public static PrintWriter out = null;
    public static BufferedReader in = null;
    public static String inputL=null;

    public Cconsole(Socket Soc)
    {
        this.channel=Soc;

        try
        {
            out=new PrintWriter(channel.getOutputStream(), true);
            in=new BufferedReader(new InputStreamReader(System.in));

            new Thread(new Cconsole(channel)).start();
        }
        catch(Exception e)
        {
            System.out.println("error in making stream from server to client");
        }
    }

    public void run ()
    {
        try
        {
            while((inputL=in.readLine())!= null )
            {
                System.out.println("CLIENT:");

                out.println(inputL);

                if (inputL.equals ("Bye.")) break;
            }



        }
        catch (Exception e)
        {
            System.out.println("Exception thrown at run loop.");
        }
    }
}

what is wrong with both the threads in each program respectively since they are hanging up?? any suggestions would be welcome :)

Edited 4 Years Ago by sleepybug: n/a

catch (Exception e)
{
System.err.println("Unknown Exception");

That's kinda dumb. The Exception knows exactly what went wrong, and in which statement, but you don't print that info. Add the following to EVERY catch in your entire system

e.printStackTrace();

Then run it again and post the resulting error message(s)

Edited 4 Years Ago by JamesCherrill: n/a

If you are using the readLine() method be sure to send an endline character. The readLine method waits until it has read all of a line before returning.

catch (Exception e)
{
System.err.println("Unknown Exception");

That's kinda dumb. The Exception knows exactly what went wrong, and in which statement, but you don't print that info. Add the following to EVERY catch in your entire system

e.printStackTrace();

Then run it again and post the resulting error message(s)

edited.

Se.java [Server]

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

public class Se
{
	public static int i=0;

	public static BufferedReader stdIn =null;

	public static void main (String [] args) throws IOException
	{
		ServerSocket serverSocket = null ;

		try {
			serverSocket = new ServerSocket (4321);
		}
		catch (IOException e)
		{
			e.printStackTrace();
			System.exit (1);
		}

		Socket clientSocket= null;

		try{
			clientSocket= serverSocket.accept();

			new Thread(new Sconsole(clientSocket)).start();
			new Thread(new Slistener(clientSocket)).start();
			
		}
		catch(Exception e)
		{
			System.err.println("Accept failed");
			e.printStackTrace();
			System.exit(1);
		}

		stdIn.close();
		clientSocket.close();
		serverSocket.close();
	}
}



class Slistener implements Runnable
{
	Socket channel=null;
	public static BufferedReader in = null;
	public static String inputL=null;
	//public static boolean closed=true;

	public Slistener(Socket Soc)
	{
		this.channel=Soc;

		try
		{
			in=new BufferedReader(new InputStreamReader(channel.getInputStream()));
			//closed=false;
		}
		catch(IOException e)
		{
			System.out.println("error in making stream from server to client");
			e.printStackTrace();
		}
		
	}
	public void run ()
	{
		try
		{
			while((inputL=in.readLine())!= null)
			{
				System.out.println("SERVER:" + inputL);

				if (inputL.equals ("Bye.")) break;
			}

		}
		catch (IOException e)
		{
			System.out.println("Exception thrown at run loop.");
			e.printStackTrace();
		}
	}
}

class Sconsole implements Runnable
{
	Socket channel=null;
	public static PrintWriter out = null;
	public static BufferedReader in = null;
	public static String inputL=null;
	//public static boolean closed=true;

	public Sconsole() {}
	
	public Sconsole(Socket Soc)
	{
		this.channel=Soc;

		try
		{
			out=new PrintWriter(channel.getOutputStream(), true);
			in=new BufferedReader(new InputStreamReader(System.in));

			//closed=false;

		}
		catch(Exception e)
		{
			System.out.println("error in writing to stream from server to client");
			e.printStackTrace();
		}
		
	}
	public void run ()
	{
		try
		{
			System.out.println("SERVER:");

			while(true)
			{
				inputL=in.readLine();

				out.println(inputL);

				if (inputL.equals ("End.")) break;
			}
			//closed=true;

		}
		catch (Exception e)
		{
			System.out.println("Exception thrown at run loop.");
			e.printStackTrace();
		}
	}
}

Cl.java

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

public class Cl extends Thread
{
	public static Socket channel= null;

	public static void main(String args[]) throws IOException
	{
		try{
			channel= new Socket ("localhost", 4321);

			System.out.println("client connected");

			new Thread(new Clistener(channel)).start();
			new Thread(new Cconsole(channel)).start();


		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.exit(1);
		}

		channel.close();
	}			
}



class Clistener implements Runnable
{
	Socket channel=null;
	public static PrintWriter out = null;
	public static BufferedReader in = null;
	public static String inputL=null;

	public Clistener() {}
	
	public Clistener(Socket Soc)
	{
		this.channel=Soc;

		try
		{
			in=new BufferedReader(new InputStreamReader(channel.getInputStream()));

			new Thread(new Clistener(channel));
		}
		catch(IOException e)
		{
			System.out.println("error in making stream from server to client");
			e.printStackTrace();
		}
		
	}
	public void run ()
	{
		try
		{
			while(true)
			{
				inputL=in.readLine();

				System.out.println("SERVER:" + inputL);

				if (inputL.equals ("Bye.")) break;
			}



		}
		catch (IOException e)
		{
			System.out.println("Exception thrown at run loop.");
		}
	}
}

class Cconsole implements Runnable
{
	Socket channel=null;
	public static PrintWriter out = null;
	public static BufferedReader in = null;
	public static String inputL=null;
	
	public Cconsole(Socket Soc)
	{
		this.channel=Soc;

		try
		{
			out=new PrintWriter(channel.getOutputStream(), true);
			in=new BufferedReader(new InputStreamReader(System.in));

			new Thread(new Cconsole(channel));
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public void run ()
	{
		try
		{
			while((inputL=in.readLine())!= null )
			{
				System.out.println("CLIENT:");

				out.println(inputL);

				if (inputL.equals ("Bye.")) break;
			}



		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}

as soon as i launch client after server,at client side it crashes after printing the same line numerous times "at Clistener.<init>(Cl.java:49)"

and at server side it continues running with some exceptions below:

at java.net.SocketInputStream.read(Unknown Source)
 at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
 at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
 at sun.nio.cs.StreamDecoder.read(Unknown Source)
 at java.io.InputStreamReader.read(Unknown Source)
 at java.io.BufferedReader.fill(Unknown Source)
 at java.io.BufferedReader.readLine(Unknown Source)
 at java.io.BufferedReader.readLine(Unknown Source)
 at Slistener.run(Se.java:74)
 at java.lang.Thread.run(Unknown Source)

all i want is simply to keep two threads in each,server and client,to keep check of reading and writing into the respective streams.would really appreciate it if you could help me with that :)

The first thing is to fix all the exceptions. You need to scroll back up your console window a bit to get the original cause of the exceptions - its the first line and it says something like
Exception in thread "xxx" java.xxx.somekindofexception at...

This code has LOTS of bugs in it.
You need to do some serious debugging.
One technique is to add lots of println statements that show the execution flow so you see where the code is executing and in what order the events occur.
Add lots of printlns. Lots and lots.
Make sure the text that each prints out is unique so you can find where it was printed.

Yes, lots of bugs. Because it's nearly Xmas I'll give you this one for free:

public Clistener(Socket Soc)  {
   ...
   new Thread(new Clistener(channel));
   ...
}

Clistener constructor contains a call to new Clistener, which causes a new Clistener to be created and its constructor to be called, which calls new.... you get the idea.

This article has been dead for over six months. Start a new discussion instead.