JAVA Socket Client TCP doesnt work very well

35 Views Asked by At

im nearly to solve this problem

I have a client and a server in localhost on port 7000

i would like to the client send message to the server that only print what it received and when the client insert QUIT both socket closed

this code partially work. I mean when client side insert QUIT the server side print all the data, but i would like to print server side everytime client send a message

//SERVER SIDE
import java.io.*;  
import java.net.*; 
public class Server3 {  
public static void main(String[] args){  
try{  
    ServerSocket ss=new ServerSocket(7000);
    Socket s=ss.accept();
        InputStream is= s.getInputStream();  
        InputStreamReader isr= new InputStreamReader(is);
        BufferedReader buffer= new BufferedReader(isr);
    while(true)
    {
        String messaggio =buffer.readLine();
        if(messaggio.equals("QUIT"))
        {
            is.close();
            ss.close();
        }
        System.out.println("messaggio ricevuto = "+ messaggio);
    }
    
    //is.close();
    //ss.close();  
}catch(Exception e){System.out.println(e);}  
}  
} 


//CLIENT SIDE
import java.io.*;  
import java.net.*;
import java.util.Scanner;
public class Client3{  
public static void main(String[] args) {  
    try{      
        Socket s=new Socket("localhost",7000);  
        OutputStream os= s.getOutputStream();
        PrintWriter pw=new PrintWriter(os);
        String messaggio;
        System.out.println("Inserisci messaggio da inviare al server:");
        Scanner scanner=new Scanner(System.in);
        while(true)
        {
        messaggio=scanner.nextLine();
        pw.println(messaggio);
            if(messaggio.equals("QUIT"))
            {
                System.out.println("SPENGO");
                pw.close();
                s.close();
                System.exit(1);
                
            }
        }
        //pw.close();
        //s.close(); 
    }catch(Exception e){System.out.println(e);}  
}  
} 

Anyone can help me ? thanks im close to the solutions

0

There are 0 best solutions below