我正在使用java中的套接字和線程構建一個多線程示例。該服務器將同時獲得多個Socket,並且當我從服務器發送消息時,我想要客戶端的套接字返回以便我給出。 到目前爲止,我的理解是創建ArrayList,但我不知道如何將其用於我的目的。 任何人都可以幫助或給我任何線索來解決這個問題?如何將數據從服務器發送到選定的客戶端?
以下是代碼:
//服務器套接字從客戶端接受之前等待。
public class ServerSocketEntry {
ServerSocket ssoc;
Socket soc;
ArrayList<Socket> arrSocket = new ArrayList<Socket>();
private static final int port=4853;
public ServerSocketEntry(ServerManagement sm){
try {
ssoc = new ServerSocket(port);
System.out.println("Waiting");
while(true){
soc=ssoc.accept();
arrSocket.add(soc);
System.out.println("Accepted: "+soc);
ServerSocketThread sth = new ServerSocketThread(soc,sm);
sth.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ServerManagement sm = new ServerManagement();
new ServerSocketEntry(sm);
}
}
// threadClass using readObject(),writeObject()方法。
public class ServerSocketThread extends Thread {
Socket soc;
ObjectOutputStream oos;
ObjectInputStream ois;
ServerManagement sm;
Food food;
public ServerSocketThread(Socket soc,ServerManagement sm) {
this.soc=soc;
this.sm=sm;
try {
ois= new ObjectInputStream(soc.getInputStream());
oos= new ObjectOutputStream(soc.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(){
Command com;
while(true){
try {
com = (Command) ois.readObject();
if(com.getCommand()==Command.Member_Check){
Member member = (Member) com.getObj();
System.out.println("thread: "+member);
if(sm.checkMember(member)){
com.setCommand(Command.Command_OK);
}else{
com.setCommand(Command.Command_Fail);
}
}else if(com.getCommand()==Command.LogIn_Check){
Member member = (Member) com.getObj();
if(sm.checkLogIn(member)){
com.setCommand(Command.Command_OK);
}else{
com.setCommand(Command.Command_Fail);
}
}else if(com.getCommand()==Command.Food_Check){
ArrayList<Food> serverArrFood = com.getFoodOrder();
if(sm.checkFood(serverArrFood)){
com.setCommand(Command.Command_OK);
}else{
com.setCommand(Command.Command_Fail);
}
}
oos.writeObject(com);
oos.flush();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
您必須使用連接到要發送到的客戶端的套接字。這只是一個數據結構問題,而且是一個微不足道的問題。 – EJP