1.创建SpringBoot Java web 项目这里当你已经熟悉Springboot
2,引入需要的WebSocket maven依赖
org.springframework.boot spring-boot-starter-websocket 3.配置webSocketpackage com.gsc.websocket.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
- 配置websocket并开启
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
4 配置客户端URL 访问地址
客户端URI访问的路径
package com.gsc.websocket.demo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
@ServerEndpoint("/websocket/{vmcNo}") // 客户端URI访问的路径
@Component
public class WebSocketServer {
/**
* 保存所有连接的webSocket实体
* CopyOnWriteArrayList使用了一种叫写时复制的方法,
* 当有新元素添加到CopyOnWriteArrayList时,
* 先从原有的数组中拷贝一份出来,然后在新的数组做写操作,
* 写完之后,再将原来的数组引用指向到新数组。
* 具备线程安全,并且适用于高并发场景
*/
private static CopyOnWriteArrayList sWebSocketServers = new CopyOnWriteArrayList<>();
private Session mSession; // 与客户端连接的会话,用于发送数据
private long mVmcNo; // 客户端的标识(这里以机器编号)
private Log mLog = LogFactory.getLog(WebSocketServer.class);
@OnOpen
public void onOpen(Session session, @PathParam("vmcNo") long vmcNo) {
mSession = session;
sWebSocketServers.add(this); // 将回话保存
mLog.info("-->onOpen new connect vmcNo is " + vmcNo);
mVmcNo = vmcNo;
}
@OnClose
public void onClose() {
sWebSocketServers.remove(this);
mLog.info("-->onClose a connect");
}
@OnMessage
public void onMessage(String message, Session session) {
mLog.info("-->onMessage " + message);
// 这里选择的是让其他客户端都知道消息,类似于转发的聊天室,可根据使用场景使用
for (WebSocketServer socketServer : sWebSocketServers) {
socketServer.sendMessage(“i have rcv you message”);
}
}
/**
* 对外发送消息
*
* @param message
*/
public boolean sendMessage(String message) {
try {
mSession.getBasicRemote().sendText(message);
} catch (IOException e) {
mLog.info(e.toString());
return false;
}
return true;
}
/**
* 对某个机器发送消息
*
* @param message
* @param vmcNo 机器编号
* @return true, 返回发送的消息, false,返回failed字符串
*/
public static String sendMessage(String message, long vmcNo) {
boolean success = false;
for (WebSocketServer server : sWebSocketServers) {
if (server.mVmcNo == vmcNo) {
success = server.sendMessage(message);
break;
}
}
return success ? message : "failed";
}
}
5,配置外部访问推送地址接口控制器
package com.gsc.websocket.demo;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WebSocketController {
//推送到某个设备的信息
@RequestMapping(value = “/operation/{vmc}/{cmd}”)
public String remote(@PathVariable(“vmc”) long vmc, @PathVariable(“cmd”) String cmd){
System.out.print(“remote”);
RemoteOperation operation = new RemoteOperation();
operation.setVmc_no(vmc);
operation.setOperation(cmd);
String message = new Gson().toJson(operation);
System.out.println(“message in json is :”+message);
return WebSocketServer.sendMessage(message,vmc);
}
@RequestMapping(value = “/test”)
public String test(){
System.out.print(“test”);
return “hello world”;
}
}
#6 以上完成后端的代码下面直接看Android代码 注明(没啥技术含量)
package com.example.administrator.myapplication;
import android.os.Bundle;
import android.os.Looper;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
/**
-
Created by Administrator on 2018/11/17.
*/
public class webSocketDemo extends AppCompatActivity {
private WebSocketClient webSocketClient;
private String TAG=“gsc”;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testwebsocket);
}
public void test(View view) {
try {
webSocketClient=new WebSocketClient(new URI(“ws://192.168.1.100:8080/websocket/1089”)) {
@Override
public void onOpen(ServerHandshake handshakedata) {
Log.d(TAG, “onOpen:”);
new Thread(){
@Override
public void run() {
super.run();
while (true){
SystemClock.sleep(2000);try { webSocketClient.send("哈哈"); }catch (Exception e){ webSocketClient.reconnect(); } } } }.start(); } @Override public void onMessage(String message) { Log.d(TAG, "message:"+message); Looper.prepare(); Toast.makeText(getApplicationContext(),"收到消息:"+message,1).show(); Looper.loop(); } @Override public void onClose(int code, String reason, boolean remote) { Log.d(TAG, "onClose:"+remote); } @Override public void onError(Exception ex) { Log.d(TAG, "onError:"+ex.getMessage()); } }; } catch (URISyntaxException e) { e.printStackTrace(); } webSocketClient.connect();
}
}
以上用到的库可以在另外学习笔记找到 https://blog.csdn.net/qq_30519365/article/details/75120475
##下面是OKHTTP实现Websocket
String url="ws://192.168.1.102:8080/websocket/1089"; //改成自已服务端的地址
OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
.readTimeout(3000, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(3000, TimeUnit.SECONDS)//设置写的超时时间
.connectTimeout(3000, TimeUnit.SECONDS)//设置连接超时时间
.build();
Request request = new Request.Builder().url(url).build();
mOkHttpClient.newWebSocket(request, new WebSocketListener() {
@Override
public void onOpen(final WebSocket webSocket, Response response) {
try {
System.out.println("onOpen"+response.body().string());
new Thread(){
@Override
public void run() {
super.run();
while (true){
SystemClock.sleep(2000);
try {
webSocket.send("哈哈");
}catch (Exception e){
}
}
}
}.start();
} catch (IOException e) {
e.printStackTrace();
}
super.onOpen(webSocket, response);
}
@Override
public void onMessage(WebSocket webSocket, String text) {
System.out.println("onMessage"+text);
super.onMessage(webSocket, text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
super.onClosing(webSocket, code, reason);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
System.out.println("onFailure"+ t.getMessage());
super.onFailure(webSocket, t, response);
}
});
最后附上源码