0

I'm trying to play around with the concurrent package and for this reason I tried to write a simple socket handler. Here is the code:

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MultiThreadedServer{
  private final static int number_of_threads = 4;
  private final static int port = 1134;

  public static void main(String[] args){  
    try{ 
      ServerSocket ss = new ServerSocket(port);
      ExecutorService pool = Executors.newFixedThreadPool(number_of_threads);
      for(;;){
        pool.execute(new SocketHandler(ss.accept()));

      }    
    }catch(Exception e){
      System.out.println(e.toString()); 

    }

  }

}

class SocketHandler implements Runnable {

  private Socket socket;  


  SocketHandler(Socket s){
    this.socket = s;
    System.out.println("-- Socket has connected -- ");


  }

  public void run(){
    try{
      BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      String s = "";
      while((s = reader.readLine()) != null  ){
        System.out.println(s);
      }
    }catch(Exception e){
      System.out.println(e.toString());
    }
  }

}

This code ^^ simply waits for sockets and reads whatever the socket sends. It works fine to an extent. ( I will explain a bit later what bothers me).

The following code is the sender class which "sends" a socket

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


public class Sender{

  public static void main(String args[]){
    try{
      int port = Integer.parseInt(args[0]);
      Socket socket = new Socket(InetAddress.getByName(null),port);
      PrintWriter writer = new PrintWriter(socket.getOutputStream());
      writer.write("Wohoo!");
      writer.close();
    }catch(Exception e){

      System.out.println(e.toString());

    }
  }


}

The code compiles fine and it even runs fine when I run my sender. However if I type

java Sender

about 3 times a second and I try to run it into my console the following thing gets printed:

java.net.BindException: Address already in use

However the whole point of this code was to not block the connections to my port and to queue the tasks. How can I tackle this?

Bula
  • 2,398
  • 5
  • 28
  • 54

1 Answers1

0

See my comment. But I think what you are seeing is exhausting your tcp ports. Are you running this thing for awhile before it starts printing port already in use? If so read ahead.

So after closing a socket there is a state of TIME_WAIT. Until it passes, you cannot reuse same port unless you have set the socket option SO_REUSEADDR.

So you need to use that option perhaps. See this answer for more insight: https://stackoverflow.com/a/14388707/520567

Community
  • 1
  • 1
akostadinov
  • 17,364
  • 6
  • 77
  • 85