简体   繁体   中英

suggestions for separate threads for socket input and output

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)).start();
            new Thread(new Slistener(clientSocket)).start();

        }
        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));
        }
        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));
        }
        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)).start();
            new Thread(new Cconsole(channel)).start();

        }
        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));
        }
        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));
        }
        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 :)

When I run your code, it doesn't hang: it crashes with StackOverflowError.

And that's expected: the constructor of Slistener invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener, which invokes the constructor of Slistener ...

Same for Clistener.

Also, the line new Thread(new Sconsole(clientSocket)); doesn't make much sense. What's the point of constructing a thread but not starting it.

Finally, starting a thread from within a constructor is a very bad practice. Never do that.

您应该首先调用客户端套接字输出流的write方法,因为客户端和服务器之间的套接字中没有任何内容,但是您首先要编写一些内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM