在Java主方法中使用WebSocket框架,首先需要选择一个WebSocket库
以Maven为例,将以下依赖添加到pom.xml文件中:
<dependencies>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.3</version>
</dependency>
</dependencies>
创建一个名为MyWebSocketServer
的类,继承org.java_websocket.server.WebSocketServer
。重写onOpen
、onClose
和onMessage
方法以处理连接打开、关闭和接收消息的事件。
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.java_websocket.WebSocket;
import java.net.InetSocketAddress;
public class MyWebSocketServer extends WebSocketServer {
public MyWebSocketServer(InetSocketAddress address) {
super(address);
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
System.out.println("Connection closed by " + (remote ? "remote peer" : "us") + " Code: " + code + " Reason: " + reason);
}
@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("Received message from " + conn.getRemoteSocketAddress().getAddress().getHostAddress() + ": " + message);
// Echo the message back to the client
conn.send("You said: " + message);
}
@Override
public void onError(WebSocket conn, Exception ex) {
ex.printStackTrace();
}
@Override
public void onStart() {
System.out.println("Server started successfully");
}
public static void main(String[] args) {
// Replace with your desired port
int port = 8887;
MyWebSocketServer server = new MyWebSocketServer(new InetSocketAddress(port));
server.run();
}
}
在main
方法中,创建一个MyWebSocketServer
实例并指定监听的端口号。然后调用run
方法启动服务器。
public static void main(String[] args) {
int port = 8887;
MyWebSocketServer server = new MyWebSocketServer(new InetSocketAddress(port));
server.run();
}
现在,当客户端连接到WebSocket服务器时,服务器将接收到消息并将其原样发送回客户端。你可以根据需要修改onMessage
方法以执行其他操作。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。