1

I am trying to open multiple ports on a server socket so that i could connect multiple clients. Each time i create a create a thread and start it (i know the overridden run method will be invoked) i open a port and listen for a client .

But the problem is that when i run the client socket project and try to connect to the port i opened in server ,it says java.net.connectException : connection refused:connect. I also noticed a peculiar thing happenning.The output in the console window is different every time i run the "server code "

i have been working on this for the last 3 days and i have achieved nothing i guess.

note: this problem is unique for me as i have not found this particular problem on this forum any where so please be kind as i am a newbie to java and socket programming though i have been coding on c++ for quite some time now .

server socket

import java.io.*;
import java.net.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.*;
public class TryThreads extends Thread
{
    private int Portnumber;
    private static String inputLine;
    public TryThreads(int portNumber)
    {
        Portnumber = portNumber;
        setDaemon(true);
    }
    public static void main(String[] args)
    {
        //create three threads
        Thread first = new TryThreads(63400);
        Thread second = new TryThreads(63401);


        first.start();
        second.start();
        //third.start();

        System.out.println("ending main");
        return;
    }
    public void run()
    {

        try
        {
            System.out.println("one socket port opened");
            ServerSocket serverSocket = new ServerSocket(Portnumber);
            System.out.println("one socket port opened");
            while (true)
            {
                System.out.println("ending main2");
                //System.out.println("one socket port opened");
                Socket clientSocket = serverSocket.accept();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                while((inputLine = bufferedReader.readLine()) != null)
                System.out.println(inputLine);
            }

        }
        catch(IOException e)
        {
            System.out.println(e);
        }
    }
}

client socket

import java.io.*;
import java.net.Socket;
public class client
{
    private static PrintWriter printWriter;
    public static void main(String[] args)
    {
        BufferedReader in = null;
        try
        {
            Socket socket = new Socket("localhost",63400);
            printWriter = new PrintWriter(socket.getOutputStream(),true);
            printWriter.println("Hello Socket");
            printWriter.println("EYYYYYAAAAAAAA!!!!");
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}
Jason C
  • 38,729
  • 14
  • 126
  • 182
user3085866
  • 125
  • 2
  • 5
  • 17
  • Sorry to ask the obvious, but have you confirmed that both ports work when you open them alone? – jgitter Feb 22 '14 at 01:34
  • 1
    You do realize you don't need "multiple ports" to handle multiple clients, yes? – Brian Roach Feb 22 '14 at 01:35
  • port did open when i had just one port and one client without using threads, after i used threads , it goes into the run block but does not go in the while block of the run block – user3085866 Feb 22 '14 at 01:36
  • I have no idea what you're trying to say in your last comment, but basically ... how you're doing it is not how you write a server. You use exactly one port. – Brian Roach Feb 22 '14 at 01:38
  • actually not , what i want (rather then need) is to open multiple ports so that clients could connect to them .i wish to create a topology this way . – user3085866 Feb 22 '14 at 01:38
  • Yes, I see your server code. That's not how you would normally write a server. – Brian Roach Feb 22 '14 at 01:40
  • @BrianRoach It's (sort of) how you write a server if you want it to listen on multiple ports (but yes the OP's motivations as stated are questionable). – Jason C Feb 22 '14 at 01:42
  • @Jason C whats OP's motivation , i dont understand – user3085866 Feb 22 '14 at 01:44
  • @JasonC Oh, I'd even question that given the loop in the Thread extending class, but yes, that's my point ... rarely is there a reason to take up multiple ports, and the OP's original comment was that they did it "so multiple clients could connect". – Brian Roach Feb 22 '14 at 01:46
  • @user3085866 OP = original poster = you. Your motivation for opening multiple ports was to support multiple clients. Assuming your description is accurate, then as Brian Roach stated: This is unnecessary, you can support multiple clients with one port. It is not directly related to the problem you are seeing, but it is a general observation about your program. – Jason C Feb 22 '14 at 01:48
  • @BrianRoach Yeah, ha, you might not have caught it but I *did* add the "(sort of)" afterwards. – Jason C Feb 22 '14 at 01:51
  • 1
    Its not about motivation right now for me , and yes i did not know that one port can handle multiple clients and i would certainly like to learn that . – user3085866 Feb 22 '14 at 01:54
  • By the way, I see you are new to StackOverflow. Thank you for including a complete compilable program and a good description of your problem. This makes it much easier for others to help you. – Jason C Feb 22 '14 at 01:57

2 Answers2

3

In your TryThreads constructor, use:

setDaemon(false);

You have set your server threads to be daemon threads and they are therefore terminating as soon as main exits, so your server is stopping as soon as you start it.

See Thread.setDaemon():

The Java Virtual Machine exits when the only threads running are all daemon threads.


By the way, after the above issue is corrected, be aware that your implementation will lead to the server receiving a "connection reset" SocketException, which will break your server thread out of its loop and prevent it from accepting additional exceptions. You can fix this on the client side by doing socket.close() before you exit to ensure a graceful shutdown, but you will still want to fix it on the server side since you cannot assume that clients will be well-behaved.
Jason C
  • 38,729
  • 14
  • 126
  • 182
  • Ha, missed that. Nice catch. – jgitter Feb 22 '14 at 01:37
  • My problem is solved,partially though :P .The ports have been opened and the client sends its message to the server and rightly said , connection has been reset. – user3085866 Feb 22 '14 at 01:48
  • But i still dont understand why threads should not be set to daemon threads and i completely dont understand the last part of your answer – user3085866 Feb 22 '14 at 01:49
  • @user3085866 The last part of my answer tried to prevent the exact "connection reset" problem you ended up seeing. In the client, do `socket.close()` before the program ends. In the server, fix your loop so it doesn't exit when a `SocketException` is received. – Jason C Feb 22 '14 at 01:53
  • @user3085866 Daemon threads are threads that do work but that you don't mind stopping when the main thread exits. Non-daemon threads are for threads that you *don't* want to stop when the main thread exits, such as your server threads (you want them to keep running after `main` returns, therefore they should not be daemons). Check out http://stackoverflow.com/questions/2213340/what-is-daemon-thread-in-java for better explanations. – Jason C Feb 22 '14 at 01:55
  • slow down a bit please :( i dont understand why should i close the socket . i want the client to have an option of terminating the connection or i want that the server haves an option of kicking the client or both. Whats the problem with the while loop in server – user3085866 Feb 22 '14 at 01:58
  • When the client closes the socket via `close()`, it properly terminates the connection and avoids the "connection reset" error on the server. Read up on stream sockets and TCP to learn more. The problem with the while loop in the server is that when the client connection is *not* closed properly, a `SocketException` is thrown (with error "connection reset") and your server exits the while loop to handle the exception. Then, it never calls `accept` again and it can't handle any more clients. If you handle the exception *inside* the server loop, the loop will keep running even after this error. – Jason C Feb 22 '14 at 02:02
  • Just keep experimenting and learning, eventually you will learn about common problems and find your own good ways to solve them. Good luck! – Jason C Feb 22 '14 at 02:02
0

Normally whenever you want to write a message using PrintWriter, you need to flush it when your done (printwriter.flush()). That makes sure the message is sent.

Peter
  • 1