简体   繁体   中英

Java sockets with thread execution

i have coded a socket listener that should listen on port 80 and 81 and when data arrive on these ports execute operations on these data. I want this listener to concurrently listen on both these ports and hav coded in the following way.

 import java.net.*;
    import java.io.*;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;

    public class MultipleSocketServer implements Runnable {

     private int a;
  private ServerSocket connection;
  private String TimeStamp;
  private int ID;
public static void main(String[] args){

       // System.out.print("ip");
     // String gh="12345";
      //System.out.println(gh.substring(1,3));
  int port = 80;
  int port1 = 81;
  int count = 0;
  double a=234.52121;

   //System.out.println(bf3.toString());
    try{

      ServerSocket socket1 = new ServerSocket(port);
      ServerSocket socket2=new ServerSocket(port1);
      System.out.println("MultipleSocketServer Initialized");
      Runnable runnable = new MultipleSocketServer(socket1, ++count);
        Runnable run = new MultipleSocketServer(socket2, ++count);
        Thread thread = new Thread(runnable);
        Thread thread1 = new Thread(run);
      while (true) {
        //Socket connection = socket1.accept();

        thread.start();
        thread1.start();
      }
    }

    catch (Exception e) {}
  }
MultipleSocketServer(ServerSocket s, int i) {
  this.connection = s;
  this.ID = i;
}
public void run() {
    while(true){


    try {
        Socket incoming=connection.accept();


            BufferedInputStream is = new BufferedInputStream(incoming.getInputStream());
            int character;
     while((character = is.read())!=-1) {
    .
    .
    do the input data handling here
    .
    .

    }
    }
    catch(Exception e){}
    }
    }
}

But for some reason this does not seem to show the threaded/conncurrent behaviour. I am testing this code using Hyperterminal, and every time i disconnect from hyperterminal, the program execution stops and "Socket is closed" exception is raised.

Any pointers would be of great help

Cheers

You're starting threads in an endless loop.

while (true) {
  //Socket connection = socket1.accept();
  thread.start();
  thread1.start();
}

I think though, that this is handled (ignored) in

} catch (Exception e) {}

However, I suspect that the problem you describe is in in the handling code you didn't include. One pretty obvious idea: you don't call connection.close() instead of incoming.close() , do you?

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