established connection between Client and Serveur, setting up basic interactions
This commit is contained in:
@@ -3,12 +3,31 @@ import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.Random;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Client {
|
||||
|
||||
private final DatagramSocket socket;
|
||||
private final InetSocketAddress address;
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
Scanner portScanner = new Scanner(System.in);
|
||||
System.out.println("Enter the server port number: ");
|
||||
int port = portScanner.nextInt();
|
||||
Client client = new Client(new InetSocketAddress("localhost", port));
|
||||
while(true) {
|
||||
Scanner scan = new Scanner(System.in);
|
||||
String message = scan.nextLine();
|
||||
client.sendMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a new client
|
||||
* @param address server adress (needed
|
||||
* @throws IOException
|
||||
*/
|
||||
public Client(InetSocketAddress address) throws IOException {
|
||||
this.address = address;
|
||||
this.socket = new DatagramSocket();
|
||||
@@ -19,7 +38,7 @@ public class Client {
|
||||
private void sendGreetings() throws IOException {
|
||||
int random = new Random().nextInt(1000);
|
||||
String machineName = "RX" + random;
|
||||
sendMessage("hello serveur " + machineName);
|
||||
sendMessage("hello Serveur, I am " + machineName);
|
||||
}
|
||||
|
||||
public void sendMessage(String message) throws IOException {
|
||||
@@ -32,7 +51,7 @@ public class Client {
|
||||
private void processHandshake(DatagramPacket packet) {
|
||||
String message = new String(packet.getData(), 0, packet.getLength());
|
||||
String machineName = message.split(" ")[1];
|
||||
System.out.println("\t[Client] Serveur " + machineName + " ready: @" + packet.getAddress().getHostAddress() + ": "
|
||||
System.out.println("↳[Client] Serveur " + machineName + " ready: @" + packet.getAddress().getHostAddress() + ": "
|
||||
+ packet.getPort());
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ public class Server {
|
||||
new Thread(this::readMessages).start();
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return this.socket.getLocalPort();
|
||||
}
|
||||
|
||||
private void sendMessage(String message, InetAddress address, int port) throws IOException {
|
||||
byte[] buffer = message.getBytes();
|
||||
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port);
|
||||
|
||||
Reference in New Issue
Block a user