【发布时间】:2014-11-28 21:55:32
【问题描述】:
我想创建一个多线程服务器,它同时与多个客户端通信。 这是问题:
- 服务器一次只能应答一个客户端。如果第一个客户端尚未收到服务器的响应,我将无法从第二个客户端发送任何内容。
这是我服务器的代码:
import java.io.*;
import java.net.*;
public class Serveur extends Thread{
private MyFrame mf;
@SuppressWarnings("unused")
private FileAttente file;
private ServerSocket serveur ;
public Serveur(int port,MyFrame f,FileAttente file) throws IOException{
serveur = new ServerSocket(port);
this.mf = f;
this.file=file;
}
@Override
public void run() {
// TODO Auto-generated method stub
mf.console.append("\nServeur en écoute ... ");
while(true){
try {
SoClient threadClient = new SoClient(this.serveur.accept());
threadClient.start();
mf.console.append("\nUn nouveau client s'est connecté");
} catch (IOException e) {e.printStackTrace();}
}
}
}
我也有这行:mf.console.append("\nUn nouveau client s'est connecté"); 在收到来自客户端的每条消息后执行。正常情况下,只有在有新客户到来时才会执行。
这是我在客户端和服务器之间放置所有操作的套接字代码:
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SoClient extends Thread {
static MyFrame mf;
FileAttente file;
public static Socket client;
public SoClient(Socket client){
this.client=client;
}
public void run(){
MyFrame.console.append("\nConnexion établi : "+client.getInetAddress());
//Envoie et reception
try {
InputStream in = this.client.getInputStream();
OutputStream out = client.getOutputStream();
sleep(2);
DataInputStream is = new DataInputStream(in);
@SuppressWarnings("deprecation")
String request = is.readLine();
MyFrame.console.append("\nMessage d'un Client :"+request);
DataInputStream din = new DataInputStream(in);
sleep(2);
String chaine_Client=din.readUTF();
MyFrame.console.append("Client :"+chaine_Client);
client.close();
} catch (IOException | InterruptedException e) {}
}
}
所以,我想做的是从服务器向所有连接的客户端发送广播消息,或者发送回显消息。 对于客户端,我创建了一个类,并根据需要尽可能多地实例化它。 Client 类和服务器类在 Eclipse 中的两个不同项目中。
【问题讨论】:
-
你试过使用Netty项目框架吗?
-
没有,我没用过
-
您是否为您的服务器查看过 RMI?它处理多个客户端同时发送到服务器的问题。对于另一种方式(广播),您的客户端还需要导出远程对象。
标签: java multithreading