I need to do a college job, where it is necessary to do TCP / IP communication something like a "chat chat" is what I have in mind to do.
But some questions have arisen, I do not know exactly how to ask them so I made a drawing in two ways that I think should be the architecture of this type of communication. I'm using the language Java
for the program, but I decided not to specify the language in the Title so that if someone from another language has the same doubt it can heal with the examples here. But if you can respond in Java
I thank you very much.
First architecture that I doubt about
Ifthisarchitectureiscorrect,thenwillIneedtoopenaThreadforeachPrivateconnectionthatapp1
willdo?Forexample:app1
communicateswithapp2
withporta99998
andifincaseyoutalktoapp3
youneedtomakeaThread
andcommunicatewithapp3
throughporta99997
?
SecondarchitecturethatIhavedoubt
InthisarchitectureallmessageswillpassServidorCentral
anditwillbeinchargeofsendingthemessagetoacertainapplication.Ifthisisthecorrectarchitecture,howcanImakeapp1
talktoapp2
?IknowitwillgothroughServidorCentral
buthowwillitknowthatthatmessagefromapp1
goestoapp2
andnottoanother?AndhowdoIsendthemessagethatisalreadyinServidorCentral
toapp
chosenbyapp1
?
Thedoubtsarethese,Ihopetheyareclear,iftheyarenotpleaseaskmetoalertmesothatIcancorrectandleaveasclearaspossible.
MaybethecodethatIdidcanhelpwithsomething,IdonotknowhowbutI'mgoingtopublishit,it'sinaverybadwaybecauseIdonotknowthemethodscompletelyandIhavenotyetformulatedagoodwaytomakeabettercommunication./p>
ClientUm
importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.BufferedReader;importjava.io.DataInputStream;//importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.Socket;publicclassClienteUm{privatestaticSocketsocket;publicstaticvoidmain(String[]args){try{socket=newSocket("127.0.0.3", 12345);
DataOutputStream fluxoSaidaDados = new DataOutputStream(socket.getOutputStream());
BufferedReader leitorBuffered = new BufferedReader(new InputStreamReader(System.in));
escreverMensagemAoServidor(fluxoSaidaDados, leitorBuffered);
lerMensagemServidor();
} catch (IOException iec) {
System.out.println(iec.getMessage());
}
}
private static void escreverMensagemAoServidor(final DataOutputStream fluxoSaidaDados, final BufferedReader leitorBuffered)
throws IOException {
new Thread() {
public void run() {
String mensagemSaida;
try {
while (true) {
mensagemSaida = leitorBuffered.readLine();
fluxoSaidaDados.writeUTF("Mensagem do Cliente (1): " + mensagemSaida + "=127.0.0.2");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
private static void lerMensagemServidor() {
new Thread(){
public void run(){
try {
DataInputStream fluxoEntradaDados = new DataInputStream(socket.getInputStream());
while(true){
String mensagemOutroClienteQueVeioPeloServidor = fluxoEntradaDados.readUTF();
System.out.println(mensagemOutroClienteQueVeioPeloServidor);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
Central Server
It is being called in the code of ServidorUm
since it was already a code that was testing before.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.SynchronousQueue;
public class ServidorUm {
private static ServerSocket servidorSocket;
private static List<Socket> socketsConectados;
public static void main(String[] args) {
try {
servidorSocket = new ServerSocket(12345);
socketsConectados = new ArrayList<Socket>();
do {
Socket socket = servidorSocket.accept();
DataInputStream fluxoEntradaDados = new DataInputStream(socket.getInputStream());
System.out.println("Cliente "+ socket.getLocalAddress().getHostAddress() +" se conectou! ");
socketsConectados.add(socket);
lerMensagemDoCliente(fluxoEntradaDados);
} while (true);
} catch (Exception e) {
System.err.println("Ops! " + e.getMessage());
}
}
private static void lerMensagemDoCliente(final DataInputStream fluxoEntradaDados) {
new Thread() {
public void run() {
String mensagemEntrada = "";
try {
while (true) {
mensagemEntrada = fluxoEntradaDados.readUTF();
String[] teste = mensagemEntrada.split("=");
String mensagem = teste[0];
String paraQuemEnviar = teste[1];
System.out.println("\n" + mensagem);
Socket socketQueReceberaMensagem = socketsConectados.stream()
.filter(x -> x.getLocalAddress().getHostAddress().equals(paraQuemEnviar))
.findFirst().get();
DataOutputStream fluxoSaidaDados = new DataOutputStream(socketQueReceberaMensagem.getOutputStream());
fluxoSaidaDados.writeUTF(mensagem);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
ClienteDois ##
import java.io.BufferedReader;
import java.io.DataInputStream;
//import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ClienteDois {
private static Socket socket;
public static void main(String[] args) {
try {
socket = new Socket("127.0.0.2", 12345);
DataOutputStream fluxoSaidaDados = new DataOutputStream(socket.getOutputStream());
BufferedReader leitorBuffered = new BufferedReader(new InputStreamReader(System.in));
escreverMensagemAoServidor(fluxoSaidaDados, leitorBuffered);
lerMensagemServidor();
} catch (IOException iec) {
System.out.println(iec.getMessage());
}
}
private static void lerMensagemServidor() {
new Thread(){
public void run(){
try {
DataInputStream fluxoEntradaDados = new DataInputStream(socket.getInputStream());
while(true){
String mensagemOutroClienteQueVeioPeloServidor = fluxoEntradaDados.readUTF();
System.out.println(mensagemOutroClienteQueVeioPeloServidor);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
private static void escreverMensagemAoServidor(final DataOutputStream fluxoSaidaDados, final BufferedReader leitorBuffered)
throws IOException {
new Thread() {
public void run() {
String mensagemSaida;
try {
while (true) {
mensagemSaida = leitorBuffered.readLine();
fluxoSaidaDados.writeUTF("Mensagem do Cliente (2): " + mensagemSaida + "=127.0.0.3");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}