[英]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.