您好我正在尝试创建一个客户端/服务器聊天程序。我有三个客户端和一个服务器,当客户端向服务器发送一些字符串时,服务器会将这个字符串发送给其他客户端。我已经创建了客户端将数据发送到服务器的部分,但我不知道如何将接收到的数据从客户端发送到其他客户端。
这是我创建的代码:
对于服务器:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Server {
private static DatagramSocket serverSocket;
public Server() {
// TODO Auto-generated constructor stub
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
serverSocket = new DatagramSocket(1111);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String s = new String( receivePacket.getData());
System.out.println("Client dit : " + s);
InetAddress IPAddress = receivePacket.getAddress();
boolean found = false;
int port = receivePacket.getPort();
sendData = s.getBytes();
}
}
}
对于客户:(X 是客户数量:client1/client2...)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ClientX {
public ClientX() {
// TODO Auto-generated constructor stub
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
System.out.println("Connécté au serveur !");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
System.out.print("Ecrire un message: ");
String s = inFromUser.readLine();
sendData = s.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 1111);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String message = new String(receivePacket.getData());
System.out.println(message);
clientSocket.close();
}
}