0
서버 (NewServer 클래스)와 클라이언트 (NewClient 클래스) 간의 통신을 설정하려고하는데 두 개의 클라이언트 통신을 수락합니다. 나는 하나의 클라이언트로 그것을하는 방법을 알고 있지만 여러 클라이언트 커넥션은 그렇지 않다.Java Multi 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.");
}
}
}