Java: 将数据从服务器发送到所有监听套接字的客户端
Java: Sending data from a server to all clients listening on the socket
我在 java swing 中创建了一个 quizServer 应用程序,它通过套接字连接到多个客户端。我能够通过套接字连接同时从每个客户端向服务器发送数据,但是当我尝试从服务器向客户端发送数据时,只有 1 个客户端接收到数据。如何修改代码以将数据同时发送给所有监听套接字的客户端?任何 code/pseudo-code 将不胜感激。
这是我的 NetworkClient class:
public class NetworkClient {
PrintWriter os = null;
Socket s1 = null;
String line = null;
BufferedReader br = null;
BufferedReader is = null;
InetAddress address = null;
void initClient() {
try {
address = InetAddress.getLocalHost();
System.out.println(address);
} catch (UnknownHostException ex) {
Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
s1 = new Socket(address, 8888); // You can use static final constant PORT_NUM
br = new BufferedReader(new InputStreamReader(System.in));
is = new BufferedReader(new InputStreamReader(s1.getInputStream()));
os = new PrintWriter(s1.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
System.err.print("IO Exception");
}
}
void sendVal(int data) {
os.println(data);
os.flush();
}
void close() {
try {
is.close();
os.close();
br.close();
s1.close();
} catch (Exception ex) {
Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
这是我的服务器 class:
public class QuizServer {
QuizJFrame frame;
ServerThread st;
void initServer(QuizJFrame frm) {
frame = frm;
Socket s = null;
ServerSocket ss2 = null;
System.out.println("Server Listening......");
try {
ss2 = new ServerSocket(8888); // port number used as 8888
} catch (IOException e) {
e.printStackTrace();
System.out.println("Server error");
}
while (true) {
try {
s = ss2.accept();
System.out.println("connection Established");
st = new ServerThread(s, frm);
st.start();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
这是服务器线程class:
class ServerThread extends Thread {
BufferedReader is = null;
PrintWriter os = null;
Socket s = null;
QuizJFrame frame;
String question[] = {"", "QUESTION 1", "QUESTION 2", "QUESTION 3", "QUESTION 4", "END"};
int answer[] = {0, 1, 2, 3, 4};
int index;
public ServerThread(Socket s, QuizJFrame frm) {
this.s = s;
frame = frm;
index = 1;
frame.setQuestion(question[index]);
}
@Override
public void run() {
int option = 0;
try {
is = new BufferedReader(new InputStreamReader(s.getInputStream()));
os = new PrintWriter(s.getOutputStream());
} catch (IOException e) {
System.out.println("IO error in server thread:" + e);
}
try {
while (option > -1) {
try {
option = Integer.parseInt(is.readLine());
os.println(answer[index] == option);
os.flush();
} catch (NumberFormatException e) { //to handle null value
}
System.out.println(result(option));
frame.output(result(option));
}
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
String result(int op) {
if (op == -1) {
return "Client exited";
}
if (answer[index] == op) {
return "Option " + op + " is the correct answer.";
} else {
return "Option " + op + " is incorrect.";
}
}
void nextQues() {
index++;
frame.setQuestion(question[index]);
os.println(-2);
os.flush();
}
}
编辑:使用 List<ServerThread>
解决了问题。
您的服务器只有一个ServerThread 变量,因此只能将数据发送到一个套接字,即最后一个添加的套接字。相反,请考虑给 class 一个 List<ServerThread>
变量以允许它与所有客户端通信。然后在创建连接的 while 循环中,将每个新创建的 ServerThread 添加到此列表中。
您还需要修复服务器的线程问题,以便 while (true)
循环不会阻塞关键代码。
您还需要升级 ServerThread class 以便主服务器对象可以与其流通信。
此外,您几乎不想 class 扩展线程。让它实现 Runnable。
我在 java swing 中创建了一个 quizServer 应用程序,它通过套接字连接到多个客户端。我能够通过套接字连接同时从每个客户端向服务器发送数据,但是当我尝试从服务器向客户端发送数据时,只有 1 个客户端接收到数据。如何修改代码以将数据同时发送给所有监听套接字的客户端?任何 code/pseudo-code 将不胜感激。
这是我的 NetworkClient class:
public class NetworkClient {
PrintWriter os = null;
Socket s1 = null;
String line = null;
BufferedReader br = null;
BufferedReader is = null;
InetAddress address = null;
void initClient() {
try {
address = InetAddress.getLocalHost();
System.out.println(address);
} catch (UnknownHostException ex) {
Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
s1 = new Socket(address, 8888); // You can use static final constant PORT_NUM
br = new BufferedReader(new InputStreamReader(System.in));
is = new BufferedReader(new InputStreamReader(s1.getInputStream()));
os = new PrintWriter(s1.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
System.err.print("IO Exception");
}
}
void sendVal(int data) {
os.println(data);
os.flush();
}
void close() {
try {
is.close();
os.close();
br.close();
s1.close();
} catch (Exception ex) {
Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
这是我的服务器 class:
public class QuizServer {
QuizJFrame frame;
ServerThread st;
void initServer(QuizJFrame frm) {
frame = frm;
Socket s = null;
ServerSocket ss2 = null;
System.out.println("Server Listening......");
try {
ss2 = new ServerSocket(8888); // port number used as 8888
} catch (IOException e) {
e.printStackTrace();
System.out.println("Server error");
}
while (true) {
try {
s = ss2.accept();
System.out.println("connection Established");
st = new ServerThread(s, frm);
st.start();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
这是服务器线程class:
class ServerThread extends Thread {
BufferedReader is = null;
PrintWriter os = null;
Socket s = null;
QuizJFrame frame;
String question[] = {"", "QUESTION 1", "QUESTION 2", "QUESTION 3", "QUESTION 4", "END"};
int answer[] = {0, 1, 2, 3, 4};
int index;
public ServerThread(Socket s, QuizJFrame frm) {
this.s = s;
frame = frm;
index = 1;
frame.setQuestion(question[index]);
}
@Override
public void run() {
int option = 0;
try {
is = new BufferedReader(new InputStreamReader(s.getInputStream()));
os = new PrintWriter(s.getOutputStream());
} catch (IOException e) {
System.out.println("IO error in server thread:" + e);
}
try {
while (option > -1) {
try {
option = Integer.parseInt(is.readLine());
os.println(answer[index] == option);
os.flush();
} catch (NumberFormatException e) { //to handle null value
}
System.out.println(result(option));
frame.output(result(option));
}
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
String result(int op) {
if (op == -1) {
return "Client exited";
}
if (answer[index] == op) {
return "Option " + op + " is the correct answer.";
} else {
return "Option " + op + " is incorrect.";
}
}
void nextQues() {
index++;
frame.setQuestion(question[index]);
os.println(-2);
os.flush();
}
}
编辑:使用 List<ServerThread>
解决了问题。
您的服务器只有一个ServerThread 变量,因此只能将数据发送到一个套接字,即最后一个添加的套接字。相反,请考虑给 class 一个 List<ServerThread>
变量以允许它与所有客户端通信。然后在创建连接的 while 循环中,将每个新创建的 ServerThread 添加到此列表中。
您还需要修复服务器的线程问题,以便 while (true)
循环不会阻塞关键代码。
您还需要升级 ServerThread class 以便主服务器对象可以与其流通信。
此外,您几乎不想 class 扩展线程。让它实现 Runnable。