通过服务器java连接两个客户端

时间:2013-11-28 17:25:32

标签: java sockets

大家好我正在尝试通过服务器连接两个客户端,atm每个客户端c连接到服务器并创建一个新线程,以便每个客户端可以与服务器通信,但我如何让两个客户端通过服务器进行通信?

服务器:

public void allowConnections(){
    int i = 0;
    try{
        while(true){                                                      
            new Thread(new TestT(draughtsSS.accept(),i )).start();         //listen for incoming connections    
            i++;
        }
    }
    catch(IOException e){
        System.out.println("Error :"+e.getMessage());
    }   
}


class TestT implements Runnable{

    Socket s;
    int gameNo;
    Scanner in;
    ObjectInputStream objectIn;  // for retrieving new color array (down s socket)
    ObjectOutputStream out;
    PrintWriter outPW;
    //String Player1;
    //String Player2;
    String playerIP;
    String opponentIP;
    int port = 50000;

    TestT(Socket s, int gameNo){
        this.s = s;
        this.gameNo = gameNo;
    }
    public void run(){

        try{
            outPW = new PrintWriter(s.getOutputStream(), true);
            out = new ObjectOutputStream(s.getOutputStream());
            out.writeObject(list);
            in = new Scanner(s.getInputStream());
            outPW.println("returnIP");                            ///get the IP of the client
            clientIPArray.add(in.nextLine());                     /// add it to the clientIPArray
        }
        catch(IOException e){
            e.getStackTrace();  
        }
        JOptionPane.showMessageDialog(new JFrame(), s.getInetAddress().toString() +" has connected.");              
        list[gameNo] = "Game "+Integer.toString(gameNo);
        gamesList.updateUI();   

        }
    }

}

    private void setupConnection(String serverIP, String port){
    int portInt = Integer.parseInt(port);
    serverIp = serverIP;
    try{
        IP = InetAddress.getByName(serverIP);
        clientSocket = new Socket(IP,portInt);
        JOptionPane.showMessageDialog(new JFrame(), "Successfully connected to Server");
        in = new ObjectInputStream(clientSocket.getInputStream());
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        scanIn = new Scanner(clientSocket.getInputStream());
        a = (String[]) in.readObject();
        if(scanIn.nextLine().equals("returnIP"))out.println(clientIp);
        getGamesList(a);
        Thread tss = new Thread(new ClientThread());
        tss.start();
        System.out.println("w");
    }
    catch(Exception e){
        System.out.println("ErrorC :" +e.getMessage());
    }
}

1 个答案:

答案 0 :(得分:0)

建议:

  • 在服务器端保留几个缓冲区,在客户端输入时刷新它们,并在连接另一个客户端时发送数据

  • 让服务器等待,直到连接两个客户端,然后将每个InputStream的{​​{1}}重定向到另一个Socket

  • 让服务器等到两个客户端连接,然后传输给另一个客户端地址,让他们通信p2p(不带服务器)

  • 上述

  • 的任意组合

最好的方法取决于你的目标。

相关问题