Java实现websocket(通过端口直接连接)

1、maven依赖

 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2、java代码
a、配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}

}

b、连接类

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;



import org.springframework.stereotype.Component;

//@ServerEndpoint("/websocket/{user}")
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;

/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1

try {
sendMessage("连接成功");
} catch (IOException e) {

}
}
// //连接打开时执行
// @OnOpen
// public void onOpen(@PathParam("user") String user, Session session) {
// currentUser = user;
// System.out.println("Connected ... " + session.getId());
// }

/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1

}

/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {


//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {

error.printStackTrace();
}


public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}


/**
* 群发自定义消息
* */
public static void sendInfo(String message) throws IOException {

for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}

public static synchronized int getOnlineCount() {
return onlineCount;
}

public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}

public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}

c、发送类

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value="/websocket")
public class WebSendController {

@RequestMapping(value="/sendToOne", produces = {"application/json; charset=utf-8"},method=RequestMethod.POST)
public void sendToOne(HttpServletRequest request,String message){
String str = message;
try {
WebSocketServer.sendInfo(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

d、页面

<!DOCTYPE html> 
<html lang="zh-CN"> 
<head> 
<meta charset="utf-8"> 
<title>网页标题-www.divcss5.com</title> 
<meta name="keywords" content="关键字" /> 
<meta name="description" content="此网页描述" /> 
</head> 
<body> 
websocket简单实现
<script> 


var socket; 
if(typeof(WebSocket) == "undefined") { 
console.log("您的浏览器不支持WebSocket"); 
}else{ 
console.log("您的浏览器支持WebSocket"); 

socket = new WebSocket("ws://192.168.1.9:8010/websocket");(通过自己的ip+端口+url连接)

//打开事件 
socket.onopen = function() { 
console.log("Socket 已打开"); 
socket.send("这是来自客户端的消息" + location.href + new Date()); 
}; 
//获得消息事件 
socket.onmessage = function(msg) { 
console.log(msg.data); 
//发现消息进入 开始处理前端触发逻辑
}; 
//关闭事件 
socket.onclose = function() { 
console.log("Socket已关闭"); 
}; 
//发生了错误事件 
socket.onerror = function() { 
alert("Socket发生了错误"); 
//此时可以尝试刷新页面
} 

}
</script> 
</body> 
</html> 

1.连接成功界面

在这里插入图片描述

2.接收消息界面

在这里插入图片描述

注:springcloud通过gateway网关实现websocket转发地址和gateway网关实现普通的转发功能地址
https://blog.csdn.net/qq_41833449/article/details/89518108

  • 2
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
要在 Java实现 WebSocket,可以使用 Java WebSocket API。以下是一个简单的示例: ```java import javax.websocket.*; import java.net.URI; @ClientEndpoint public class MyWebSocketClient { @OnOpen public void onOpen(Session session) { System.out.println("Connected to endpoint: " + session.getBasicRemote()); } @OnMessage public void onMessage(String message) { System.out.println("Received message: " + message); } public static void main(String[] args) { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); String uri = "ws://localhost:8080/myendpoint"; try { Session session = container.connectToServer(MyWebSocketClient.class, URI.create(uri)); session.getBasicRemote().sendText("Hello, World!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们定义了一个 `MyWebSocketClient` 类,并使用 `@ClientEndpoint` 注解将其标记为 WebSocket 客户端端点。我们还定义了两个注解方法,`onOpen()` 和 `onMessage()`,分别在连接建立和接收到消息时被调用。在 `main()` 方法中,我们使用 `WebSocketContainer` 来连接WebSocket 终端点,并向其发送一条消息。 在使用上述代码之前,需要确保已经引入 Java WebSocket API 的依赖项。可以使用以下 Maven 依赖项: ```xml <dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.1</version> </dependency> ``` 注意,以上代码仅适用于通过端口直接连接WebSocket。如果需要使用 SSL/TLS 连接,或者需要进行身份验证等操作,需要进行额外的配置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值