简体   繁体   English

套接字服务器客户端不显示输出

[英]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:我正在 java 中的服务器套接字项目上工作,客户端应该向服务器发送消息,服务器读取它然后将其转换为大写,但我不确定为什么我没有得到 output,它是temp最后,它没有被转换,它是一个套接字 tcp/ip 程序,这是我的客户端程序:

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:这将为服务器创建 output:

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.如果在这一点上,你的客户端仍然没有给你预期的 output,你有一些编译问题。 In that case, check your compiler output.在这种情况下,请检查您的编译器 output。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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