1.前言
前兩天我一個(gè)開發(fā)好友跑過來問我websocket的問題,雖然搭建出來了,但是就是不成功!之前我沒搭建過,只是之前的開發(fā)妹子搭建的我參考用的,里面大致原因什么的我也不是很清楚。今天來解釋一下何為WebSocket !
先了解一下http請(qǐng)求和WebSocket區(qū)別:
http協(xié)議是用在應(yīng)用層的協(xié)議,他是基于tcp協(xié)議的,是一問一答模式,要求每次請(qǐng)求都要三次握手才能發(fā)送自己的信息
而WebSocket沒有這個(gè)限制,為了解決客戶端發(fā)起多個(gè)http請(qǐng)求到服務(wù)器資源瀏覽器必須要經(jīng)過長(zhǎng)時(shí)間的輪訓(xùn)問題而生的,他實(shí)現(xiàn)了多路復(fù)用,他是全雙工通信。在webSocket協(xié)議下客服端和瀏覽器可以同時(shí)發(fā)送信息。websocket是為聊天誕生的,聊天不用等朋友一問一答那樣,想怎么聊發(fā)多少自己決定。開始今天重點(diǎn)吧!
2.依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>websocket</groupId>
<artifactId>websocket</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring session -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<!-- websocket dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<finalName>SpringSession</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin </artifactId>
</plugin>
</plugins>
</build>
</project>
3.配置作用:首先要注入ServerEndpointExporter,這個(gè)bean會(huì)自動(dòng)注冊(cè)使用了@ServerEndpoint注解聲明的Websocket endpoint。
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();
}
}
4.ServerEndpoint注解
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
/**
* Created by 螃蟹和駱駝先生Yvan on 2018/8/24.
*/
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
//靜態(tài)變量,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。
private static int onlineCount = 0;
//concurrent包的線程安全Set,用來存放每個(gè)客戶端對(duì)應(yīng)的MyWebSocket對(duì)象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//與某個(gè)客戶端的連接會(huì)話,需要通過它來給客戶端發(fā)送數(shù)據(jù)
private Session session;
/**
* 連接建立成功調(diào)用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數(shù)加1
System.out.println("有新連接加入!當(dāng)前在線人數(shù)為" + getOnlineCount());
try {
sendMessage("歡迎來到歡樂一家?。?!");
} catch (IOException e) {
System.out.println("IO異常");
}
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數(shù)減1
System.out.println("有一連接關(guān)閉!當(dāng)前在線人數(shù)為" + getOnlineCount());
}
/**
* 收到客戶端消息后調(diào)用的方法
*
* @param message 客戶端發(fā)送過來的消息*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("來自客戶端的消息:" + message);
//群發(fā)消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 發(fā)生錯(cuò)誤時(shí)調(diào)用
@OnError
**/
public void onError(Session session, Throwable error) {
System.out.println("發(fā)生錯(cuò)誤");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
this.session.getAsyncRemote().sendText(message);
}
/**
* 群發(fā)自定義消息
* */
public static void sendInfo(String message) throws IOException {
for (WebSocketServer item : webSocketSet) {
System.out.println("錢勇萬牛逼!??!");
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--;
}
}
4.Controller層
import com.websocket.lease.config.WebSocketServer;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by 螃蟹和駱駝先生Yvan on 2018/8/24.
*/
@Controller
public class WebController {
@RequestMapping(value="/publicSend",method= RequestMethod.GET)
public String pushVideoListToWeb2(String id) {
return "success";
}
}
5.啟動(dòng)類APP
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
/**
* Created by 螃蟹和駱駝先生Yvan on 2018/8/24.
*/
@SpringBootApplication
public class App extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
6.application.properties配置類
spring.thymeleaf.prefix=classpath:/templates/
7.success.html成功類 存放在/main/java/resource/templates/
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
/**
* Created by 螃蟹和駱駝先生Yvan on 2018/8/24.
*/
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
//靜態(tài)變量,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。
private static int onlineCount = 0;
//concurrent包的線程安全Set,用來存放每個(gè)客戶端對(duì)應(yīng)的MyWebSocket對(duì)象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//與某個(gè)客戶端的連接會(huì)話,需要通過它來給客戶端發(fā)送數(shù)據(jù)
private Session session;
/**
* 連接建立成功調(diào)用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數(shù)加1
System.out.println("有新連接加入!當(dāng)前在線人數(shù)為" + getOnlineCount());
try {
sendMessage("螃蟹和駱駝先生Yvan?。?!");
} catch (IOException e) {
System.out.println("IO異常");
}
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數(shù)減1
System.out.println("有一連接關(guān)閉!當(dāng)前在線人數(shù)為" + getOnlineCount());
}
/**
* 收到客戶端消息后調(diào)用的方法
*
* @param message 客戶端發(fā)送過來的消息*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("來自客戶端的消息:" + message);
//群發(fā)消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 發(fā)生錯(cuò)誤時(shí)調(diào)用
@OnError
**/
public void onError(Session session, Throwable error) {
System.out.println("發(fā)生錯(cuò)誤");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);//getBasicRemote是阻塞式的同步 比如2個(gè)發(fā)送,要兩個(gè)同步發(fā)送完成,第一個(gè)發(fā)送快要結(jié)束,第二個(gè)發(fā)送一點(diǎn)點(diǎn),第一個(gè)就要等第二個(gè)
this.session.getAsyncRemote().sendText(message);//getAsyncRemote是非阻塞式的異步,建議使用
}
/**
* 群發(fā)自定義消息
* */
public static void sendInfo(String message) throws IOException {
for (WebSocketServer item : webSocketSet) {
System.out.println("錢勇萬你真牛逼");
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--;
}
}
8.測(cè)試結(jié)果是兩個(gè):因?yàn)槲矣昧俗枞陌l(fā)送方法getBasicRemote和非阻塞發(fā)送方法getAsyncRemote():

發(fā)送兩次
代碼地址鏈接: https://pan.baidu.com/s/1q1SI23zVAOwV-JUBucm31g 密碼: 6w2i