用到的工具和技术.
1.微信web开发工具小程序版
2.Myeclipse 2014
3.WebSocket
4.Maven 3.3.9
5.Tomcat 7
步骤
1.安装配置Maven,使用Myeclipse创建web project 使用Maven项目结构. 具体步骤:点击打开链接
2.打开微信web开发工具,由于是内部开发测试,故不要填写 appID, 创建新项目,把项目放在Maven项目目录下 src/main/webapp/项目名
3.创建Websocket 实现握手通信.
以下代码均来自网络资料.
java服务器端:
- package websocketTest;
-
- import java.io.IOException;
- import java.util.concurrent.CopyOnWriteArraySet;
-
- import javax.websocket.*;
- import javax.websocket.server.ServerEndpoint;
-
-
-
-
-
- @ServerEndpoint("/websocket")
- public class TestWebSocket {
-
- private static int onlineCount = 0;
-
-
- private static CopyOnWriteArraySet<TestWebSocket> webSocketSet = new CopyOnWriteArraySet<TestWebSocket>();
-
-
- private Session session;
-
-
-
-
-
- @OnOpen
- public void onOpen(Session session){
- this.session = session;
- webSocketSet.add(this);
- addOnlineCount();
- System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
- }
-
-
-
-
- @OnClose
- public void onClose(){
- webSocketSet.remove(this);
- subOnlineCount();
- System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
- }
-
-
-
-
-
-
- @OnMessage
- public void onMessage(String message, Session session) {
- System.out.println("来自客户端的消息:" + message);
-
- for(TestWebSocket item: webSocketSet){
- try {
- item.sendMessage(message);
- } catch (IOException e) {
- e.printStackTrace();
- continue;
- }
- }
- }
-
-
-
-
-
-
- @OnError
- public void onError(Session session, Throwable error){
- System.out.println("发生错误");
- error.printStackTrace();
- }
-
-
-
-
-
-
- public void sendMessage(String message) throws IOException{
- this.session.getBasicRemote().sendText(message);
-
- }
-
- public static synchronized int getOnlineCount() {
- return onlineCount;
- }
-
- public static synchronized void addOnlineCount() {
- TestWebSocket.onlineCount++;
- }
-
- public static synchronized void subOnlineCount() {
- TestWebSocket.onlineCount--;
- }
- }
- <pre name="code" class="javascript">var app = getApp()
- Page({
- onLoad:function(){
-
- wx.connectSocket({
- url: "ws://localhost:8080/TestYMG/websocket",
- })
- wx.onSocketOpen(function() {
- console.log('WebSocket连接已经打开!')
- wx.sendSocketMessage({
- data: 'HELLO,WORLD'+Math.random()*0XFFFFFF.toString()
- })
- });
- wx.onSocketMessage(function(data) {
- console.log(data);
- });</pre><pre name="code" class="javascript">
- wx.onSocketClose(function() {
- console.log('WebSocket连接已经关闭!')
- });
- },</pre><pre name="code" class="javascript">
- setclose:function(e){
- console.log('WebSocket连接正在关闭!')
- wx.closeSocket();
-
- }
-
-
- })
- </pre><br>
- <p></p>
- <pre></pre>
- <p></p>
-
原文地址http://www.bieryun.com/671.html