添加一个线程,每次只处理1个套接字

时间:2013-10-04 18:19:38

标签: java multithreading sockets

如何在该代码中添加一个Thread,每次只允许1个连接......当它完成时.close();再打开等待另一个?我尝试了很多其他的东西,如WHILE,if和其他变量,但未能阻止.accept();连接是开放的; /,我不知道如何使它成为一个线程

import java.awt.Desktop;
import java.io.*;
import java.lang.reflect.Array;
import java.net.*;
import java.util.ArrayList;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Provider  {
    ServerSocket providerSocket;
    Socket connection = null;
    ObjectOutputStream out;
    String ocupado = "0";
    ObjectInputStream in;
    String caminhodoarquivo;
    Provider(){}
    void run()
    {
        try{
            providerSocket = new ServerSocket(2004, 1);
            System.out.println("---------------Aguardando por certidões----------------");          
            connection = providerSocket.accept();  
            out = new ObjectOutputStream(this.connection.getOutputStream());
            out.flush();
            sendMessage(ocupado);
            in = new ObjectInputStream(connection.getInputStream());

            System.out.println("Certidão de: " + connection.getInetAddress().getHostName());
            String ocupado = "1";


                try{
                    caminhodoarquivo = (String)in.readObject();
                   System.out.println("Certidão: " + caminhodoarquivo);

                   JTextField paginainicial = new JTextField();
                   JTextField paginafinal = new JTextField();
                   Object[] message = {
                        "Número da Primeira Folha: ", paginainicial,
                        "Número Última Folha: ", paginafinal,
                    };

                int option = JOptionPane.showConfirmDialog(null, message, "Dados da Certidão", JOptionPane.OK_CANCEL_OPTION);
                ocupado = "1";
                if (option == JOptionPane.OK_OPTION) {

                    String primeirafolha = paginainicial.getText();
                    String ultimafolha = paginafinal.getText();
                    metodos metodosBD = new metodos();
                    metodosBD.atualizafolha(primeirafolha, ultimafolha, caminhodoarquivo);

                    System.out.println("Dados inseridos.");
                    Desktop.getDesktop().print(new File(caminhodoarquivo)); 
                    ocupado = "0";


                } else {
                    System.out.println("Certidão Cancelada.");

                }


                }
                catch(ClassNotFoundException classnot){
                    System.err.println("Data received in unknown format");
                    out.close();
                    in.close();
                    providerSocket.close();
                }



        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
        finally{
            //4: Closing connection
            try{
                in.close();
                out.close();
                providerSocket.close();
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }

    void sendMessage(String msg)
    {
        try{
            out.writeObject(msg);
            out.flush();
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
    }
    public static void main(String args[])
    {
        Provider server = new Provider();
        while(true){
            server.run();
        }
    }

}
  

编辑user2511414的答案

1)服务器运行正常并完全接收第一个连接并在我关闭confirmdialog时完成它,我可以完全打开另一个= OK

2)当我连接client1时,保持confirmdialog打开,并尝试连接第二个客户端我在CLIENT2中重现此错误:

java.net.SocketException: Software caused connection abort: recv failed
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.read(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
        at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
        at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Sour
ce)
        at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
        at java.io.ObjectInputStream.<init>(Unknown Source)
        at certidoesOrganizado.PrimeiroPDF$Requester.run(PrimeiroPDF.java:151)
        at certidoesOrganizado.PrimeiroPDF.enviacaminho(PrimeiroPDF.java:132)
        at certidoesOrganizado.PrimeiroPDF.geracertidao(PrimeiroPDF.java:466)
        at certidoesOrganizado.PrimeiroPDF.pegadados(PrimeiroPDF.java:302)
        at certidoesOrganizado.gui$6.actionPerformed(gui.java:204)

并且在服务器中我重温了这个:

java.net.SocketException: Socket is closed
        at java.net.Socket.getOutputStream(Unknown Source)
        at Provider.run(Provider.java:21)
        at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-4" java.lang.NullPointerException
        at Provider.run(Provider.java:59)
        at java.lang.Thread.run(Unknown Source)

并且Client2没有收到“服务器忙碌消息”

3)当client1 ConfirmDialog仍然打开时,在Client2失败后我尝试了CLIENT3,它连接成功,我以2个Joption.ShowConfirmDialog打开... :(

并且一切都重新开始,我在CLIENT中使用它来进行连接:

在调用连接的方法中:

Requester client = new Requester();

client.run();

班级请求者:

}
class Requester{
    Socket requestSock

et;
        ObjectOutputStream out;
    ObjectInputStream in;
    String message;

    Requester(){}
    void run()



    {




        try{

                requestSocket = new Socket("localhost", 2004);



            System.out.println("Tentando Conexão");
            out = new ObjectOutputStream(requestSocket.getOutputStream());
            out.flush();            
            System.out.println("out.flush");
            in = new ObjectInputStream(requestSocket.getInputStream());

                try {
                    message = (String)in.readObject();
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }







            do{
               message = "oi";
                sendMessage(arquivonomecompleto);
            }while(message.equals("bye"));

        }
        catch(UnknownHostException unknownHost){
            System.err.println("You are trying to connect to an unknown host!");
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
        finally{
            //4: Closing connection
            try{
                in.close();
                out.close();
                requestSocket.close();
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }


    }

    void sendMessage(String msg)
    {
        try{
            out.writeObject(msg);
            out.flush();
            //System.out.println("client>" + msg);
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
    }




}

1 个答案:

答案 0 :(得分:2)

我看到你的代码是单线程,没有其他线程的迹象,一切都是由主线程运行的,第二我对某些部分有点困惑,首先你在得到之后刷新输出,我的意思是你不发送任何东西冲洗它!

out = new ObjectOutputStream(this.connection.getOutputStream());
out.flush();

所以你如何看待你的应用程序并行运行?!

关于在另一个线程(和单个)中运行连接进程,这不是一个非常困难的工作,首先实现Runnable接口,让run方法处理连接处理。

public class Provider implements Runnable  {
  ...
  public void run(){//manages the connection but ONE at a time.
    while(true){
       server.run();
    }
  }
  public static void main(String[] arg){
    Provider server = new Provider();
    new Thread(this).start();//start the connection processing with another thread.
  }
  ...
}

你也会有一个简单的thread tutorial here。 有一个很好的并行程序伙计:)

UPDATE:并且在第一个进程中拒绝第二个(有一些消息),所以这也不是一个艰难的工作,但首先是让进程并行为此,我将main方法(cut)放入另一个类中,让Provider类处理请求,同时保持ServerSocket(端口)OEPN。

import java.awt.Desktop;
import java.io.*;
import java.lang.reflect.Array;
import java.net.*;
import java.util.ArrayList;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Provider implements Runnable {
   // ServerSocket providerSocket;
    Socket connection = null;
    ObjectOutputStream out;
    String ocupado = "0";
    ObjectInputStream in;
    String caminhodoarquivo;
    Provider(Socket s){this.connection=s;}
    @Override
    public void run()
    {
        try{
            out = new ObjectOutputStream(this.connection.getOutputStream());
            //out.flush();
            sendMessage(ocupado);
            in = new ObjectInputStream(connection.getInputStream());
            System.out.println("Certidão de: " + connection.getInetAddress().getHostName());
            String ocupado = "1";
                try{
                    caminhodoarquivo = (String)in.readObject();
                   System.out.println("Certidão: " + caminhodoarquivo);
                   JTextField paginainicial = new JTextField();
                   JTextField paginafinal = new JTextField();
                   Object[] message = {
                        "Número da Primeira Folha: ", paginainicial,
                        "Número Última Folha: ", paginafinal,
                    };
                int option = JOptionPane.showConfirmDialog(null, message, "Dados da Certidão", JOptionPane.OK_CANCEL_OPTION);
                ocupado = "1";
                if (option == JOptionPane.OK_OPTION) {
                    String primeirafolha = paginainicial.getText();
                    String ultimafolha = paginafinal.getText();
                    metodos metodosBD = new metodos();
                    metodosBD.atualizafolha(primeirafolha, ultimafolha, caminhodoarquivo);
                    System.out.println("Dados inseridos.");
                    Desktop.getDesktop().print(new File(caminhodoarquivo)); 
                    ocupado = "0";
                }else {System.out.println("Certidão Cancelada.");}
                }catch(ClassNotFoundException classnot){
                    System.err.println("Data received in unknown format");
                    out.close();
                    in.close();
                    connection.close();
                }
        }
        catch(IOException ioException){ioException.printStackTrace();}
        finally{
            Server.setFree();//Tells server the system is ready for new connection.
            //4: Closing connection
            try{
                in.close();
                out.close();
                connection.close();
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }

    void sendMessage(String msg)
    {
        try{
            out.writeObject(msg);
            out.flush();
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
    }
//    public static void main(String args[])
//    {
//        Provider server = new Provider();
//        while(true){
//            server.run();
//        }
//    }

}

注意:当服务器忙时,这一响应“错误 - &gt;服务器忙”作为字符串,因此客户端需要检查服务器响应单字符串“错误 - &gt;服务器是否忙”这意味着服务器没有回应其他任何事情。

class Server implements Runnable{
  private final String serverBusyMessage="Error -> Server is busy";
  private ServerSocket ss;
  private static volatile boolean busy=false;
  public static void setFree(){busy=false;}
  public void run(){
    while(true){
       try{Socket s=ss.accept();
           if(busy){//if there is one connection processing.
              ObjectOutputStream out=new ObjectOutputStream(s.getOutputStream());
              out.writeObject(serverBusyMessage);
              out.flush();
              s.close();continue;
           }
           System.out.println("---------------Aguardando por certidões----------------");   
           new Thread(new Provider(s)).start();
           busy=true;
       }catch(Exception e){}
    }
  }
  private Server(){try{ss=new ServerSocket(2004);}catch(Exception ex){}}
  public static void main(String[] arg){
    Server server = new Server();
    new Thread(server).start();
  }
}