[RESOLVIDO]Chat cliente/servidor usando sockets

2 respostas
java
X

E ae pessoal, beleza?
Sou tão novo no fórum quanto sou novo com java. Não tenho conhecimento de linguagens orientadas a objetos, mas estou fazendo um chat usando sockets. Dei uma procurada nos threads aqui do fórum e nao consegui resolver meu problema. Eu consigo enviar mensagens do “cliente” pro “servidor”, mas não o inverso. Como é um chat, o ideal seria os dois lados enviarem e receberem as mensagens.

Este é o código do cliente

package client;

import <a href="http://java.io">java.io</a>.<em>;

import <a href="http://java.net">java.net</a>.</em>;

import java.util.Scanner;

public class Client {
public static void main(String[] args) throws IOException {

Scanner teclado = new Scanner(System.in);
System.out.println("Host address:");
    String host = teclado.nextLine();
    System.out.println("Host port: ");
    int port= teclado.nextInt();
    
        Socket cliente = new Socket(host, port);
        System.out.println("Connection Established: "); 
            
        PrintStream saida = new PrintStream(cliente.getOutputStream()); 
        while (teclado.hasNextLine()) {
            saida.println(teclado.nextLine());
        }
            
    }
}

E este é o codigo do servidor:

package server;

import <a href="http://java.net">java.net</a>.<em>;

import <a href="http://java.io">java.io</a>.</em>;

import java.util.Scanner;

public class Server {
public static void main(String[] args) throws IOException {

Scanner teclado = new Scanner(System.in);
    System.out.println("Host port: ");
    int port= teclado.nextInt();
    
        ServerSocket servidor = new ServerSocket(port);
        System.out.println("Server listening on " + port);      
        Socket cliente = servidor.accept();
        System.out.println("Client " + cliente.getInetAddress().getHostAddress() + " connected on " + port);
Scanner entrada = new Scanner(cliente.getInputStream());
        while(entrada.hasNextLine()){
            System.out.println(entrada.nextLine());
        }
        entrada.close();
        servidor.close();
}

}

Falta algo nos códigos para essa conversa bidirecional funcionar? Ou eu devo rodar um servidor e um cliente numa maquina, e outro cliente na outra para funcionar do jeito que eu preciso?
Valeu pessoal

2 Respostas

C

O material da Caelum é bem didático nesse exemplo e pode te tirar várias dúvidas, além de te dar novas ideias:

https://www.caelum.com.br/apostila-java-orientacao-objetos/apendice-sockets

X

Obrigado Cindy :smiley:
resolvi o problema quatro dias atrás. A solução foi usar uma “thread” no lado do servidor. O código ficou assim:

import <a href="http://java.net">java.net</a>.<em>;

import <a href="http://java.io">java.io</a>.</em>;

import java.util.Scanner;
public class Server {

static Socket cliente;

static ServerSocket servidor;

public static void main(String[] args) throws IOException {
Scanner teclado = new Scanner(System.in);
    System.out.println("Host port: ");
    int port= teclado.nextInt();
    
    servidor = new ServerSocket(port);
    System.out.println("Server listening on " + port);      
    cliente = servidor.accept();
    System.out.println("Client " + cliente.getInetAddress().getHostAddress() + " connected on " + port);
Thread t = new Thread(new Runnable() {

public void run() {

try { 	

Scanner entrada = new Scanner(cliente.getInputStream());

while(entrada.hasNextLine()){

String text = entrada.nextLine();

if(text.equals("[q]")) {

break;

}

System.out.println(text);

}

entrada.close();

cliente.close();

servidor.close();

} catch(Exception e) {
}
  }
});

t.start();

Thread t1 = new Thread(new Runnable() {

public void run() {

try {           	

PrintStream saida = new PrintStream(cliente.getOutputStream());

while (teclado.hasNextLine()) {

String palavra = teclado.nextLine();

if(palavra.equals("[q]")) {

<a href="//saida.println">//saida.println</a>(“Client disconnected”);

saida.println(palavra);

break;

} else {

saida.println(teclado.nextLine());

}

}

servidor.close();

cliente.close();

} catch(Exception e) {
}
  }
});

t1.start();

//   servidor.close();

}

}

Problema resolvido :slight_smile: se precisarem, podem fechar o tópico

Criado 3 de julho de 2016
Ultima resposta 10 de jul. de 2016
Respostas 2
Participantes 2