Java 如何在服务器端创建应该给出响应的侦听器?
嗨,我正在用SpringBoot构建项目,并使用socket编程在客户端和服务器之间进行通信。我已经在本地主机上启动了我的项目,端口号为8080。 我使用以下代码运行我的客户端程序:Java 如何在服务器端创建应该给出响应的侦听器?,java,spring,websocket,spring-boot,Java,Spring,Websocket,Spring Boot,嗨,我正在用SpringBoot构建项目,并使用socket编程在客户端和服务器之间进行通信。我已经在本地主机上启动了我的项目,端口号为8080。 我使用以下代码运行我的客户端程序: String serverName = "localhost"; int port = 8080; try { System.out.println("Connecting to " + serverName + " on port "
String serverName = "localhost";
int port = 8080;
try {
System.out.println("Connecting to " + serverName + " on port "
+ port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
System.out.println("Hello from " + client.getLocalSocketAddress());
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
此程序打印消息“刚连接到127.0.0.1:8080”,但在“client.close”上方的行引发异常:
我的要求是如何在服务器端创建侦听器,该侦听器可以处理来自客户端的消息并返回一些响应我检查了您的代码。连接正常,但当您在.readUTF()中使用时,客户端不会从服务器响应 您可以使用以下代码: 字符串serverName=“localhost”; int端口=8080
try {
System.out.println("Connecting to " + serverName + " on port "
+ port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
System.out.println("Hello from " + client.getLocalSocketAddress());
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
if (in.read() != -1) {
System.out.println("Server says " + in.readUTF());
}
client.close();
} catch (IOException e) {
e.printStackTrace();
}
因为spring引导在tomcat上运行,而tomcat只理解HTTP。因此,这里您的客户机连接到tomcat服务器,它只能理解HTTP。因此,如果您希望通过HTTP连接到spring boot应用程序,那么请通过TCP连接将HTTP请求发送到spring boot应用程序。否则,在SpringBoot应用程序上实现一个组件,该组件可以在其他端口上接受TCP连接,并根据您的协议进行处理
try {
System.out.println("Connecting to " + serverName + " on port "
+ port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
System.out.println("Hello from " + client.getLocalSocketAddress());
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
if (in.read() != -1) {
System.out.println("Server says " + in.readUTF());
}
client.close();
} catch (IOException e) {
e.printStackTrace();
}