Java client / server

chiaraberti13

Nuovo Utente
1 Lug 2019
1
0
1
Salve sto provando a risolvere questo esercizio, ma temo di aver sbagliato qualcosa poichè client e server non comunicano..

Scrivere due classi java Client e Server con queste caratteristiche:
Server: Accetta dei messaggi dal client (inviati come linee di testo) e le restituisce al client stesso numerandole.
Client: Il client invia dei messaggi in linee di testo al server.
La connessione viene chiusa all’arrivo della stringa “basta”.
Es.:
<il client invia> “Ciao server!”;
<il client riceve> “Messaggio 1: Ciao server!”
<il client invia> “Che bella giornata!”;
<il client riceve> “Messaggio 2: Che bella giornata!” ...

Server
Codice:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package esercizio_capitolo_12_3;
import java.net.*;
import java.io.*;
/**
 *
 * 
 */
public class server {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        ServerSocket s = null;
        try{
        s = new ServerSocket (9999);
        System.out.println("Server avviato sulla porta 9999 ");
        } catch (IOException e) {
         e.printStackTrace();
        }
    while (true){
    try {
    Socket s1 = s.accept();
    OutputStream s1out = s1.getOutputStream();
    BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (s1out));
    bw.write("Ciao client sono il server!");
    System.out.println("Messaggio spedito a "+s1.getInetAddress());
    bw.close();
    s1.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }   
    }   
    }

Client
Codice:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package esercizio_capitolo_12_3;
import java.net.*;
import java.io.*;
/**
 *
 * 
 */
public class client {
    public static void main(String[] args) {
try {
String host = "127.0.0.1";
Socket s = new Socket(host, 9999);
BufferedReader br = new BufferedReader (new InputStreamReader(s.getInputStream()));
System.out.println(br.readLine());
br.close();
s.close();
}catch (ConnectException connExc){
System.err.println("Non riesco a connettermi al server");
}catch (IOException e){   
System.err.println("Problemi....");   
}
}
}
 

Discussioni simili