Java多客户端服务器套接字

时间:2016-10-16 23:06:25

标签: java sockets server client serversocket

我正在尝试在服务器(NewServer类)和客户端(NewClient类)之间建立通信,接受两个客户端通信。我知道如何使用一个客户端但不是多个客户端连接。

  • 我是否必须在Client类中创建2个读者?

  • 我可以以递归方式执行此操作吗?

服务器类:

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

public class NewServer
{
    //Create Server Socket and a Client Socket for each Client.
    static ServerSocket server;
    static Socket client1;
    static Socket client2;

    //Create OutputStreams to send information to each Client.
    static DataOutputStream client1writer;
    static DataOutputStream client2writer;

    static final int PORT = 9999;

    //Main Method
    public static void main(String[]args)
    {
        //Try-Catch Block for Socket Errors.
        try
        {
            //Create the Server Socket as a Host.
            server = new ServerSocket(PORT);

            //Connect Client 1 – First run of the Client class.
            client1 = server.accept();
            client1writer = new    
            DataOutputStream(client1.getOutputStream());

            //Connect Client 2 – Second run of the Client class.
            client2 = server.accept();
            client2writer = new     
            DataOutputStream(client2.getOutputStream());            

            //Assign each Client an ID number – this is how the Client will know
            //    which individual Client it’s representing in RunTime.
            int ID1 = 8675309;
            int ID2 = 8675308;

            //Tell both Clients which one they are representing.
            client1writer.writeInt(ID1);
            client2writer.writeInt(ID2);

            //Close all Sockets when finished.
            client1.close();
            client2.close();
            server.close();
        }
        catch (IOException IOex)
        {
            System.out.println("Server Error.");
        }
    }
}

客户端类:

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

public class NewClient {

    static Socket client = null;                          
    static final int PORT = 9999;                      
    static final String IP = "localhost";                

    public static void main(String[] args) throws IOException {

        int id1;      
        int id2;                      

        try{
            client = new Socket(IP,PORT);      
            System.out.println("Connection successful!");

            reader = new DataInputStream(client.getInputStream());

            id1 = reader.readInt();
            id2 = reader.readInt();       

            System.out.println("The id of the user is " + id);

            //Closing everything
            client.close();
            reader.close();

        }catch(IOException error) {
            System.err.println("Server error.");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以通过为每个新客户端连接启动一个单独的线程(也称为普通线程)来实现它,然后调用在循环中运行的server.accept()。它可用作学习例如,但是当你失去对线程的控制时,无法帮助你实现所需的功能。

第二种方法是使用 Executor Service ,它可以更好地管理上述解决方案。