Skip to content

Instantly share code, notes, and snippets.

@ShawonAshraf
Created August 27, 2024 02:14
Show Gist options
  • Save ShawonAshraf/b03dde786b4e238edc227c63bd0e8589 to your computer and use it in GitHub Desktop.
Save ShawonAshraf/b03dde786b4e238edc227c63bd0e8589 to your computer and use it in GitHub Desktop.
package org.playerchat.core;
import org.playerchat.utils.MessageCounter;
import org.playerchat.utils.MessageLogger;
import org.playerchat.utils.Operations;
import java.io.*;
import java.net.Socket;
public class PlayerMultiProcess {
private final String name;
private final int port;
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private MessageCounter counter;
public PlayerMultiProcess(String name, int port) throws IOException {
this.name = name;
this.port = port;
this.counter = new MessageCounter();
System.out.println("Player:: " + this.name + " is connecting to port: " + this.port);
this.socket = new Socket("localhost", port);
this.out = new PrintWriter(socket.getOutputStream(), true);
this.in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()
)
);
}
public void sendMessage(String message) {
this.counter.incrementOutgoingMessages();
MessageLogger.log(
this.name,
Operations.SENT,
message
);
this.out.println(message);
}
public void receiveMessage(String message) {
MessageLogger.log(
this.name,
Operations.RECEIVED,
message
);
// increase counter
this.counter.incrementIncomingMessages();
// send ack
String ackMessage = "PriorMessage:: " + message + "\tResponse:: ACK";
this.sendMessage(ackMessage);
}
public void start() {
new Thread(() -> {
try {
String message;
while ((message = in.readLine()) != null) {
String messageWithCounter = message + " " + this.counter.getIncomingMessages();
this.receiveMessage(messageWithCounter);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
private void closeStreams() {
try {
this.in.close();
this.out.close();
this.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
String name = args[0];
int port = Integer.parseInt(args[1]);
PlayerMultiProcess player = new PlayerMultiProcess(name, port);
player.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment