简体   繁体   English

如何使用 Java Socket 监听客户端?

[英]How do I listen to the client using the Java Socket?

I'm working with "ServerSocket" and "Socket", the problem I'm going through is this: I create a server using serverSocket, I'm waiting for the client to connect, when it connects I'll receive some information, and here's my question, how do I keep listening to the client and receive instructions from it?我正在使用“ServerSocket”和“Socket”,我遇到的问题是:我使用 serverSocket 创建了一个服务器,我正在等待客户端连接,当它连接时我会收到一些信息,这是我的问题,我如何继续听取客户的意见并接受客户的指示?

In the example below I am creating a server, when the client connects I save the connection within the "clientSocket ".在下面的示例中,我正在创建一个服务器,当客户端连接时,我将连接保存在“clientSocket”中。

@GET
@Path("/createServer")
public String conect() throws IOException { 
    
    serverSocket = new ServerSocket(3242);      
    clientSocket = serverSocket.accept();
    ...
    ...
  }

From this point I need to always listen to this clientSocket, when the client send some information I need to capture to perform some actions, how to do that?从这一点开始我需要一直监听这个clientSocket,当客户端发送一些我需要捕获的信息来执行一些动作时,该怎么做呢?

ServerSocket.accept() gives you a java.net.Socket . ServerSocket.accept()给你一个java.net.Socket Doc here文档 在这里

From there on, you can read on that socket using its input stream ( Socket.getInputStream() ) or write to its output stream ( Socket.getOutputStream() )从那里开始,您可以使用其输入 stream ( Socket.getInputStream() )读取该套接字或写入其 output stream (SocketOutputStream)( Socket.getOutputStream()

Your sockets (client and server) will live until they're close d, or garbage collected, so remember to keep a strong reference to each one as long as you need them.您的 sockets(客户端和服务器)将一直存在,直到它们close d 或垃圾收集,因此请记住,只要您需要它们,就对它们保持强烈的引用。

Sample programs (simple echo server. Type bye in client to exit):示例程序(简单的回显服务器。在客户端中键入bye退出):

Server.java服务器.java

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Server {

  private static volatile boolean stopped = false;

  public static void main(String[] args) throws IOException, InterruptedException {

    try (ServerSocket server = new ServerSocket(3001)) {
      System.out.println("Server ready to accept connections on port " + server.getLocalPort());

      final Socket client = server.accept();
      System.out.println("Client connected using remote port " + client.getPort());

      final Thread t = new Thread(() -> {
        try {
          try (InputStream clientIn = client.getInputStream()) {
            try (OutputStream clientOut = client.getOutputStream()) {
              echo(clientIn, clientOut);
            }
          }
        } catch (IOException ioe) {
          ioe.printStackTrace();
          stopped = true;
        }
      });
      t.setDaemon(true);
      t.start();

      while (!stopped) {
        Thread.sleep(10);
      }
      System.out.println("Program exit");

    }

  }

  private static void echo(InputStream clientIn, OutputStream clientOut) throws IOException {
    
    try (Scanner clientScan = new Scanner(clientIn, StandardCharsets.UTF_8)) {
      try (OutputStreamWriter clientWriter = new OutputStreamWriter(clientOut, StandardCharsets.UTF_8)) {
        
        while (!stopped) {
          final String fromClient = clientScan.nextLine();
          System.out.println("In: " + fromClient);
          clientWriter.write(fromClient);
          clientWriter.write(System.lineSeparator());
          clientWriter.flush();
          if ("bye".equalsIgnoreCase(fromClient.trim())) {
            stopped = true;
          }
        }
        System.out.println("Loop done");
        
      }
    }
    
  }

}

Client.java客户端.java

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
  private static volatile boolean stopped = false;

  public static void main(String[] args) throws UnknownHostException, IOException {
    System.out.println("Client launched");
    try (Socket client = new Socket("localhost", 3001)) {
      System.out.println("Connected on remote port " + client.getPort() + " from " + client.getLocalPort());

      try (Scanner console = new Scanner(System.in)) {
        try (OutputStreamWriter toServer = new OutputStreamWriter(client.getOutputStream())) {

          final Thread t = new Thread(() -> printEverything(client));
          t.setDaemon(true);
          t.start();

          while (!stopped) {
            final String fromConsole = console.nextLine();
            if (stopped)
              break;
            toServer.write(fromConsole);
            toServer.write(System.lineSeparator());
            toServer.flush();
          }

        }
      }

    }
    System.out.println("Program exit");

  }

  private static void printEverything(Socket client) {
    try (Scanner server = new Scanner(client.getInputStream())) {
      while (!stopped) {
        final String fromServer = server.nextLine();
        System.out.println("Server said: " + fromServer);
        if ("bye".equalsIgnoreCase(fromServer.trim())) {
          stopped = true;
        }
      }
      System.out.println("Loop done. Press enter to exit");
    } catch (IOException e) {
      e.printStackTrace();
      stopped = true;
    }
  }

}

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

相关问题 如何使用服务器套接字在Java中一次监听一个客户端? - how to listen to one client at a time in java using server socket? 如何使用Java Socket监听80端口 - How to listen to port 80 by using Java Socket 如何在套接字编程中从Server(server.java)socket连续侦听PHP(client.php)套接字 - how to continuously listen PHP(client.php) socket from Server(server.java)socket in socket programming 如何使用Java在接口/设备上侦听网络流量? - How do I listen for network traffic on an interface/device using Java? 我如何将Java套接字客户端连接到多个服务器 - How do i connect java socket client to multiple servers 如何从Java中的套接字获取客户端名称? - How do I get the client name from a socket in Java? 如何在Java 7中为RMI配置自定义客户端套接字工厂? - How do I configure a custom client socket factory for RMI in Java 7? 如何在Java的单独线程中运行客户端套接字? - How do I run my client socket in seperate threads in Java? 如何使用 Socket 将客户端连接到 Java 中的服务器 - How can I connect a client to a server in Java using Socket 使用Caesar Cipher身份验证用Java编写客户端服务器套接字程序时,我需要知道什么? - What do I need to know to write a client server socket program in Java using Caesar Cipher authentication?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM