• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Java的WebSocket

武飞扬头像
小逗比iswho
帮助1

1、前端:

<javascript>
	var socket=null;
	if("WebSocket" in window){
		//if(window.websocket){}
		//注意websocket走的时websocket协议,发请求时协议是ws://
		socket=new WebSocket(ws://127.0.0.1:8888/socketTest);
	}else{
		alert("您的浏览器不支持websocket");
	}
	//建立连接后要干的事情
	socket.onopen=function(event){
		console.log("连接已经建立,开始发送消息")
		socket.send("message")
	}
	//关闭连接后要干的事情
	socket.onclose=function(){
		console.log("连接已经关闭")
	}
	//收到服务端消息后要干的事情
	socket.onmessage=function(message){
		console.log("收到来自服务端的消息" message)
	}
	//连接出错要干的事情
	socket.onerror=function(exception){
		console.log("连接出错,请检查网络!")
	}
	
</javascript>
学新通

2、后端:

@compenent
@ServerEndPoint()
//@ServerEndPoint将当前类作为一个socket服务器
public class WebSocket{
	public Session session;
	@onOpen
	//@onOpen是socket建立连接时所要执行的方法
	public void onOpen(Session session){
		this.session=session;
	}
	@onClose
	//@onClose是socket关闭时所要执行的方法
	public void onClose(){
		system.out.print("连接已经断开")
	}
	@onMessage
	//@onMessage是socket收到消息时时所要执行的方法
	public void onMessage(String message){
		system.out.print("收到来自客户端的消息:" message)
	}
	@onError
	//@onError是socket收到消息时时所要执行的方法
	public void onError(Throwable error)throws error{
		t.printStackTrace();
	}
	//广播:后端发给前端的消息
	public void sendMessage(String message){
		this.session.getBasicRemote().sendText(message);
	}
}
学新通

3、后端还需在IOC容器中注入ServerEndpointExporter,需要在pom文件中添加依赖:spring-boot-starter-websocket

@Configuration
public class SocketConfig{
	@Bean
	public ServerEndpointExporter getServerEndpoint(){
		return new ServerEndpointExporter();
	}
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgekkfj
系列文章
更多 icon
同类精品
更多 icon
继续加载