简体   繁体   中英

Socket server client doesn't show ouput

i'm working on a server socket project in java, where the client should send a message to server, the server reads it then converts it to uppercase, but i'm not sure why i don't get the output,which is temp in the end, it doesn't get converted,its a socket tcp/ip program, here is my client program:

import java.io.*;
import java.net.*;
import java.util.Scanner;
class SocketClient {
public static void main(String argv[]) {
int port = 1234;
try {
Scanner s1=new Scanner(System.in);
Socket s=new Socket("localhost",port);
Scanner sc=new Scanner(s.getInputStream());
System.out.println("Enter a word to convert :");
String m=s1.nextLine();

PrintStream p=new PrintStream(s.getOutputStream());
p.println(m);
String temp=sc.nextLine();
System.out.println("the converted word is :"+temp.toUpperCase());


} catch (UnknownHostException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}}}

and my server program is:

import java.io.*;
import java.net.*;
import java.util.Scanner;
public class SocketServeur {
public static void main(String argv[]) {
int port = 1234;
try {
    ServerSocket ss= new ServerSocket(port);
    Socket so=ss.accept();
    Scanner s1=new Scanner(so.getInputStream());
    String m=s1.nextLine();
    String temp=m;
    PrintStream p=new PrintStream(so.getOutputStream());
    
    p.println(temp);
    

} catch (Exception e) {
System.err.println("Error : " + e);
}
}

}

I blew up your example a bit. The server will and can handle multiple clients simultaneously. For advanced strategies you would put Server and Client in their own files, grant advanced controllability and restrict access to variables. Also, read the comments in the source code.

It is important to start the Server before the Client; else you will get connection errors.

package stackoverflow.socketprinters;

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class SocketServeur {
    static public final int SERVER_PORT = 1234;



    public static void main(final String argv[]) {
        final int port = SERVER_PORT;
        System.out.println("Creating socket on port " + port + "...");
        try (final ServerSocket serverSocket = new ServerSocket(SERVER_PORT);) {
            while (!serverSocket.isClosed()) {
                System.out.println("Server waiting for connection...");
                @SuppressWarnings("resource") final Socket socket = serverSocket.accept(); // will be closed in handleClient()
                startClientHandler(socket); // you could also use Executors.newFixedThreadPool(amount), see https://www.baeldung.com/thread-pool-java-and-guava
            }

        } catch (final Exception e) {
            System.err.println("Error : " + e);
        }
    }

    private static void startClientHandler(final Socket pSocket) {
        System.out.println("\tStarting handler for " + pSocket.getRemoteSocketAddress() + "...");
        final String threadName = "handleClient(" + pSocket.getRemoteSocketAddress() + ")";
        final Thread socketThread = new Thread(() -> handleClient(pSocket), threadName);
        socketThread.setDaemon(false); // Thread will die and release resources when ServerSocket gets closed.
        socketThread.start();
    }

    private static void handleClient(final Socket pSocket) { // only using a method here, usually client handling is done in its own class
        System.out.println("\tHandling request for " + pSocket.getRemoteSocketAddress() + "...");

        try (final Scanner socketScanner = new Scanner(pSocket.getInputStream());
                final PrintStream socketPrintstream = new PrintStream(pSocket.getOutputStream());) {

            final String readMessage = socketScanner.nextLine();
            final String processedMessage = readMessage.toUpperCase();
            socketPrintstream.println(processedMessage);

        } catch (final Exception e) {
            System.err.println("Error : " + e);
        } finally {
            try {
                pSocket.close();
            } catch (final Exception e2) { /* ignore */ }
            System.out.println("\tRequest handled for " + pSocket.getRemoteSocketAddress());
        }
    }

}

and

package stackoverflow.socketprinters;

import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

class SocketClient {
    public static void main(final String argv[]) {
        try (final Scanner sysinScanner = new Scanner(System.in);
                final Socket socket = new Socket("localhost", SocketServeur.SERVER_PORT);
                final Scanner socketScanner = new Scanner(socket.getInputStream());
                final PrintStream socketPrintstream = new PrintStream(socket.getOutputStream());) {

            System.out.print("Enter a word to convert: ");
            final String message = sysinScanner.nextLine();
            socketPrintstream.println(message);

            System.out.println("Converting...");

            final String receivedMessage = socketScanner.nextLine();
            System.out.println("the converted word is: '" + receivedMessage + "'");

        } catch (final Exception e) {
            e.printStackTrace();
        }

        System.out.println("Client closing now...");
    }
}

This will create output for the Server:

Creating socket on port 1234...
Server waiting for connection...  
    Starting handler for /127.0.0.1:49970...  
Server waiting for connection...  
    Handling request for /127.0.0.1:49970...  
    Request handled for /127.0.0.1:49970  
    Starting handler for /127.0.0.1:49977...  
Server waiting for connection...  
    Handling request for /127.0.0.1:49977...  
    Request handled for /127.0.0.1:49977  

And for the clients something like:

Enter a word to convert: dasdsadas
Converting...
the converted word is: 'DASDSADAS'
Client closing now...

If, at this point here, your Client still does not give you the expected output, you have some compilation problems. In that case, check your compiler output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM