刚开始研究Java后端,在用maven测试websocket,用的是 Java WebSockets A barebones WebSocket client and server implementation written 100% in Java - 1.5.2 - a Java package on Maven - Libraries.io https://libraries.io/maven/org.java-websocket:Java-WebSocket 。
主要代码:
//Server.java file
package com.my.app;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
public class Server extends WebSocketServer {
public Server() throws UnknownHostException {
}
public Server(int port) throws UnknownHostException {
super(new InetSocketAddress(port));
System.out.println("websocket Server start at port: " + port);
}
@Override
public void onOpen(WebSocket conn, ClientHandshake clientHandshake) {
System.out.println("new connection ===" + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
/**
*省略代码
*/
@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("you have a new message: " + message);
// 向客户端发送消息
conn.send(message);
}
/**
* 启动服务端
* @param args
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException {
new Server(9996).start();
}
}
}
<!-- pom.xml文件增加的依赖 -->
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.1</version>
</dependency>
这个代码在windows本地,使用vscode可以运行:
把工程弄到 centos上,打包正常,运行时出现:
Error: Could not find or load main class com.my.app.Server
如图: