多客户端服务器请求处理程序

时间:2016-06-25 05:03:26

标签: java sockets request client serversocket

我需要在java中实现一个接受客户端连接的服务器(没有限制),然后客户端向服务器发出请求,服务器应该响应请求,但只响应发出请求的客户端。我不知道如何从这开始...... 我可以使它工作1对1连接,我知道如何进行多客户端聊天,其中服务器响应每个人,但我怎样才能从服务器选择客户端响应,只是为了使得请求??

package negocio;

import java.io.*;
import java.net.*;
//import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Servidor {
    private ServerSocket servidor;
    private Socket cliente;
    private OutputStream os;
    private ObjectInputStream ois;
    private InputStream is;
    private DataInputStream leerS;
    private DataOutputStream escribirS;
    private ObjectOutputStream oos;


    public Servidor(){
        try {
            servidor = new ServerSocket(5000);
            System.out.println("creador serv");
            cliente = new Socket();
            cliente = servidor.accept();
            System.out.println("cliente conec");
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    public String recibirString(){
        String mens = ""; 
        try {
             leerS = new DataInputStream(cliente.getInputStream());
             mens =  "Mensaje del cliente: "+leerS.readUTF();
         } catch (IOException ex) {
             Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
         }
        return mens;
    }


    public Object recibirObjeto(){
     System.out.println("Recibiendo");
       try {
        ois = new ObjectInputStream(cliente.getInputStream());
        return ois.readObject();
       } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("llego nullo");
        return null;
       }
     }

    public void enviarObjeto(Object obj){
        try {
            oos = new ObjectOutputStream(cliente.getOutputStream());
            oos.writeObject(obj);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }

}

0 个答案:

没有答案