Java线程从套接字退出

时间:2015-05-16 10:28:27

标签: java multithreading sockets

大家好我写了一个小的聊天应用程序,创建一个带有静态IP地址的套接字,当我输入newconn后,它创建一个新的对象类并启动一个新的线程,在另一个端口创建一个连接。我的问题是,当我想要关闭连接所有连接的特定端口,例如:

连接启动whit端口4455,输入:newconn,插入端口例如4488,如果我输入后:退出连接丢失,连接在两者上关闭,在4455和4488中。我的英文不好我希望你可以帮助我。这是我的来源:

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

 class connection implements Runnable{

   String host;
   int port;

 void setconnection(String h, int pp){

  host=h;
  port=pp;

}

public void run() {

 try {
          Socket mysocket = new Socket(host, port);


        PrintWriter out =
            new PrintWriter(mysocket.getOutputStream(), true);


        BufferedReader in =
            new BufferedReader(
                new InputStreamReader(mysocket.getInputStream()));  

  while (true) {

      out.println("Insert command:>");

      switch (in.readLine()){


     case "hello":
     out.println("hello from client");
     break;


     case "newconn":
       try{
       out.println("Insert port");
       String nwport=in.readLine();
       int ppn=Integer.parseInt(nwport);
       connection provola= new connection();
       provola.setconnection("127.0.0.1",ppn);
       Thread t;
       t= new Thread(provola);
       t.start();

 }catch(IOException e){
   out.println("error");
 }
       break;
       case "exit":
       out.println("bye bye ;)");
       mysocket.close();
       break;
       default:
       out.println("error");


       }

}//end while


} catch (UnknownHostException e) {
        System.err.println("Nnnn " );
        System.exit(1);
    } catch (IOException e) {
        System.err.println("unable to establish connection " 
            );
        System.exit(1);
    } 

}


 }


public class Chat{

 public static void main(String[] args) throws IOException {
 Thread t;
 connection test= new connection();
 t= new Thread(test);
 test.setconnection("127.0.0.1",4455);
 t.start();

 }
}

0 个答案:

没有答案