我有一个服务器 - 客户端程序,我希望使用JLabel(MouseClick)
与所有连接的客户端进行通信。但该消息仅传递给最后连接的客户端。我无法确定问题所在。这是我的代码
//服务器
void connect_clients()
{
try {
ServerSocket listener = new ServerSocket(7700);
jButton1.setText("Server Running!");
jButton1.setEnabled(false);
try {
while (true) {
socket = listener.accept();
try {
clientIP = socket.getLocalAddress().getHostName();
}
catch(Exception e){}
}
}
catch(Exception e){}
}
catch(IOException ex)
{
}
}
}
private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {
PrintWriter out;
try {
out = new PrintWriter(socket.getOutputStream(), true);
out.println("pc2");
} catch (IOException ex) {
Logger.getLogger(third_frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
//客户端
void connect_server()
{
try {
while(true)
{
// TODO code application logic here
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
s = new Socket(serverAddress, 7700);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
answer = null;
}
}
catch (IOException ex) {
Logger.getLogger(client_form.class.getName()).log(Level.SEVERE, null, ex);
}
}
注意:Socket
在服务器和客户端都是全局声明的。
答案 0 :(得分:0)
每次服务器接受连接时,它都会创建一个代表它的新套接字。由于每次建立新连接时都会覆盖套接字引用,因此您只保留对最后一个连接的引用。
private List<Socket> socketList;
...
ServerSocket listener = new ServerSocket(7700);
socketList = new ArrayList<>();
...
socketList.add(listener.accept());
...
for (Socket socket: socketList) {
out = new PrintWriter(socket.getOutputStream(), true);
out.println("pc2");
...
}