我正在構建一個多線程聊天服務器應用程序,它將廣播一個客戶端發送給所有客戶端的消息。在Internet上的大多數示例和Oracle的網站太廣播是使用udp(多播套接字)完成的,但我使用tcp。 有誰知道如何發送消息到所有連接的客戶端在TCP連接? 這裏是我當前的代碼工作正常,並將從客戶端receieved的消息,只有客戶端:如何在java中使用tcp將消息廣播到所有客戶端
EchoServer的
import java.net.*;
import java.io.*;
public class EchoServer
{
public static void main(String[] args)
throws IOException
{
if (args.length != 1) {
System.err.println("Usage: java EchoServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0]));
while (true) {
try {
Thread t = new Thread(new MultiServer(serverSocket.accept()));
t.start();
} catch(IOException e) {
System.out.println("Accept Failed:");
System.exit(-1);
}
}
}
}
EchoClient
import java.io.*;
import java.util.Scanner;
import java.net.*;
public class EchoClient
{
public static void main(String[] args) throws IOException
{
if (args.length != 2) {
System.err.println("Usage: java EchoClient <host name><portnumber>");
System.exit(1);
}
String hostName = "localhost";
int portNumber = Integer.parseInt(args[1]);
try (
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo::" + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + hostName);
System.exit(1);
}
}
}
多服務器
import java.io.*;
import java.net.*;
public class MultiServer implements Runnable
{
private Socket client;
public MultiServer(Socket m)
{
this.client = m;
}
@Override
public void run()
{
BufferedReader in = null;
PrintWriter out = null;
try {
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch(IOException ignored) {
}
while (true) {
String line;
try {
while ((line = in.readLine()) != null)
out.println(line);
} catch (IOException e) {
System.out.println("Read Failed");
System.exit(-1);
}
}
}
}
TCP不支持廣播,**但是**您可以簡單地將相同的消息發送給每個客戶端。 – immibis
如何做到這一點?我們可以使用arrayList嗎? –
您必須維護您自己的已連接客戶端的線程安全列表,然後只要需要發送廣播消息就可以遍歷該列表。只要確保您的通信協議設計用於支持隨時從服務器發送給客戶端的未經請求的消息,並且您執行的每個客戶端都以線程安全的方式發送,以避免多個線程同時發送重疊的消息。否則,你將很容易破壞你的通信。 TCP廣播並不是微不足道的正確管理。 –