socket服务器客户端不显示输出

bvn4nwqk  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(364)

我正在用java开发一个服务器套接字项目,在这个项目中,客户机应该向服务器发送一条消息,服务器读取该消息,然后将其转换为大写,但我不确定为什么我没有得到输出,这是 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();
}}}

我的服务器程序是:

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);
}
}

}

csbfibhn

csbfibhn1#

我把你的例子搞砸了。服务器可以同时处理多个客户端。对于高级策略,您可以将服务器和客户机放在它们自己的文件中,授予高级可控性并限制对变量的访问。另外,请阅读源代码中的注解。
在客户端之前启动服务器是很重要的;否则会出现连接错误。

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());
        }
    }

}

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...");
    }
}

这将为服务器创建输出:

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

对于客户来说,比如:

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

如果此时,您的客户机仍然没有提供预期的输出,那么您就有一些编译问题。在这种情况下,请检查编译器输出。

相关问题