我创建了一个Android应用程序,其中,android应用程序充当客户端,服务器驻留在桌面应用程序中。
假设有10个Android应用程序在10个不同的Android平板电脑上同时运行相同,当从一个平板电脑收到一个更新时,桌面应用程序将更新发送到所有其他剩余的平板电脑。服务器如何知道连接的客户端数量以及如何将消息发送给所有客户端
我计划在所有Android中运行服务器,以便当从一个平板电脑收到一个更新时,桌面应用程序会将更新发送给所有其他剩余的平板电脑。
任何人都可以告诉我一些有关此事的建议。
客户端
private int SERVER_PORT = 9999;
class Client implements Runnable {
private Socket client;
private PrintWriter out;
private Scanner in;
@Override
public void run() {
try {
client = new Socket("localhost", SERVER_PORT);
Log.d("Client", "Connected to server at port " + SERVER_PORT);
out = new PrintWriter(client.getOutputStream());
in = new Scanner(client.getInputStream());
String line;
while ((line = in.nextLine()) != null) {
Log.d("Client", "Server says: " + line);
if (line.equals("Hello client")) {
out.println("Reply");
out.flush();
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
服务器类
class ServerThread implements Runnable {
private ServerSocket server;
@Override
public void run() {
try {
server = new ServerSocket(SERVER_PORT);
Log.d("Server", "Start the server at port " + SERVER_PORT
+ " and waiting for clients...");
while (true) {
Socket socket = server.accept();
Log.d("Server",
"Accept socket connection: "
+ socket.getLocalAddress());
new Thread(new ClientHandler(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandler implements Runnable {
private Socket clientSocket;
private PrintWriter out;
private Scanner in;
public ClientHandler(Socket clietSocket) {
this.clientSocket = clietSocket;
}
@Override
public void run() {
try {
out = new PrintWriter(clientSocket.getOutputStream());
in = new Scanner(clientSocket.getInputStream());
String line;
Log.d("ClientHandlerThread", "Start communication with : "
+ clientSocket.getLocalAddress());
out.println("Hello client");
out.flush();
while ((line = in.nextLine()) != null) {
Log.d("ClientHandlerThread", "Client says: " + line);
if (line.equals("Reply")){
out.print("Server replies");
out.flush();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
您可以将套接字保存在列表中,并通过该列表中的所有OutputStream发送消息:
Socket socket = Server.accept();
sockets.add(socket); //sockets is an ArrayList<Socket>
public void sendMessageToEveryone(String msg) {
for(Socket s : sockets) {
s.getOutputStream().write(msg.getBytes());
s.getOutputStream().flush();
}
答案 1 :(得分:0)
您可以使用Google Cloud Messaging服务。
看一下这个页面: https://developer.android.com/google/gcm/index.html