开发者

Java sockets with thread execution

开发者 https://www.devze.com 2022-12-17 17:16 出处:网络
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 port

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.toStr开发者_Python百科ing());
    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?

0

精彩评论

暂无评论...
验证码 换一张
取 消