websocket服务端JAVA_java编写WebSocket服务端

本文档介绍了如何使用JAVA实现WebSocket服务端,包括连接请求处理、Tomcat8中的WebSocket支持以及服务端的关键方法如`@OnOpen`、`@OnMessage`、`@OnClose`和`@OnError`。通过示例代码展示了WebSocket服务端如何接收和发送消息,并管理客户端连接。
摘要由CSDN通过智能技术生成

WbSocket官方协议内容: http://datatracker.ietf.org/doc/rfc6455/?include_text=1

连接请求内容:

服务端接收请求后主要是成针对Sec-WebSocket-Key生成对就Sec-WebSocket-Accept 的key,生成Sec-WebSocket-Accept值比较简单就是Sha1(Sec-WebSocket-Key+258EAFA5-E914-47DA-95CA-C5AB0DC85B11)即可

在Tomcat8中集成了websocket-api.jar.他对WebSocket协议进行的封装:

package com.lgy.websocket;

import java.io.IOException;

import java.util.Set;

import java.util.concurrent.CopyOnWriteArraySet;

import java.util.concurrent.atomic.AtomicInteger;

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;

@ServerEndpoint(value = "/websocket/chat")

public class HelloWebSocketServlet {

//private static final Log log = LogFactory.getLog(ChatAnnotation.class);

private static final String GUEST_PREFIX = "Guest";

private static final AtomicInteger connectionIds = new AtomicInteger(0);

private static final Set connections = new CopyOnWriteArraySet<>();

private final String nickname;

private Session session;

public HelloWebSocketServlet() {

nickname = GUEST_PREFIX + connectionIds.getAndIncrement();

}

//建立连接

@OnOpen

public void start(Session session) {

this.session = session;

connections.add(this);

String message = String.format("* %s %s", nickname, "has joined.");

System.out.println(message);

}

//接受消息

@OnMessage

public void incoming(String message) {

System.out.println(message.toString());

//broadcast(filteredMessage);

broadcast(message.toString());

}

//客户端关闭了连接

@OnClose

public void end() {

connections.remove(this);

String message = String.format("* %s %s", nickname, "has disconnected.");

System.out.println(message);

//broadcast(message);

}

//WebSocket服务出错

@OnError

public void onError(Throwable t) throws Throwable {

//log.error("Chat Error: " + t.toString(), t);

}

private static void broadcast(String msg) {

for (HelloWebSocketServlet client : connections) {

try {

synchronized (client) {

client.session.getBasicRemote().sendText(msg);

}

} catch (IOException e) {

//log.debug("Chat Error: Failed to send message to client", e);

connections.remove(client);

try {

client.session.close();

} catch (IOException e1) {

// Ignore

}

String message = String.format("* %s %s",

client.nickname, "has been disconnected.");

broadcast(message);

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值