文档章节

websocket服务端,android客户端示例

Hackway
 Hackway
发布于 2016/03/02 01:55
字数 1184
阅读 431
收藏 2

服务端库依赖详见章末

#####spring websocket服务端代码(会话过程)

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(HandshakeInterceptor.class);

    //会话开始
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        attributes.put(Constant.WEBSOCKET_USERNAME,"LSH");
        //  从session中获取用户
        /*if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
            HttpSession session = serverHttpRequest.getServletRequest().getSession(false);
            if (session!=null) {
                String username = (String) session.getAttribute(Constant.SESSION_USERNAME);
                attributes.put(Constant.WEBSOCKET_USERNAME,username);
            }
        }*/
        return true;
    }

    //会话结束
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        System.out.println("After Handshake");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}

#####服务端websocket消息处理

import com.beesgame.sanguo.constant.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by hackway on
 * Date: 2016/1/15.
 * Time:11:15
 */
public class WebSocketEndPoint extends TextWebSocketHandler {

    private static final ArrayList<WebSocketSession> users;
    private static final Logger logger;

    static {
        users = new ArrayList<WebSocketSession>();
        logger = LoggerFactory.getLogger(WebSocketEndPoint.class);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");
        session.sendMessage(returnMessage);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.info("connect to the websocket success......");
        //添加用户到session
        users.add(session);
        String username = (String) session.getAttributes().get(Constant.WEBSOCKET_USERNAME);
        if (username!=null) {
            session.sendMessage(new TextMessage("用户名:"+username));
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        logger.info("websocket transport error, connection closed......");
        users.remove(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        logger.info("websocket connection closed......");
        users.remove(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return super.supportsPartialMessages();
    }

    // 发送信息给特定用户(LSH)
    public void sendMessageToUser(String username, TextMessage message) {
        for (WebSocketSession user:users) {
            if (user.getAttributes().get(Constant.WEBSOCKET_USERNAME).equals(username)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }

     //发送信息给所用用户,广播
    public void sendMessageToAllUser(TextMessage message) {
        for (WebSocketSession user:users) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

#####使用注解配置websocket(需要在springmvc配置文件中开启相应注解支持)

@Configuration
//@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry.addHandler(getWebSocketEndPoint(),"/websocket").addInterceptors(new HandshakeInterceptor());
        webSocketHandlerRegistry.addHandler(getWebSocketEndPoint(),"/websocket/sockjs").addInterceptors(new HandshakeInterceptor()).withSockJS();
    }

    @Bean
    public WebSocketEndPoint getWebSocketEndPoint() {
        return new WebSocketEndPoint();
    }
}

#####controller调用websocket发送信息

@Controller("/*")
public class IndexController extends BaseController {



    @Autowired
    private UserInfoService userInfoService;
    
    //注入websocket
    @Bean
    public WebSocketEndPoint getWebSocketEndpoint() {
        return new WebSocketEndPoint();
    }

    @RequestMapping(value = "socket.do", produces = "text/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String socket(@RequestParam(value = "uid") long uid) throws IOException {
        UserInfoVO userToken = userInfoService.getUserInfoVOByUid(uid);
        String result = objectMapper.writeValueAsString(userToken);
        getWebSocketEndpoint().sendMessageToUser("LSH", new TextMessage(result));
        return result;
    }
}

#####服务端启动截图 
输入图片说明

#####客户端websocket链接服务端(android) java-websocket 项目地址 https://github.com/TooTallNate/Java-WebSocket

gradle中添加java-websocket依赖 ######compile 'org.java-websocket:Java-WebSocket:1.3.0'

#####websocket客户端类

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.Date;

/**
 * Created by hackway on 16/2/24.
 */
public class SiteWebsocket extends WebSocketClient {


    //handler通知主线程更新textview
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            textView.setText(String.valueOf(msg.obj));
        }
    };
    private TextView textView;
    public SiteWebsocket(URI serverUri, Draft draft, TextView tv) {
        super(serverUri, draft);
        this.textView = tv;
    }
    @Override
    public void onOpen(ServerHandshake handshakedata) {
        Log.d("websocket","open connection");
    }

    @Override
    public void onMessage(String message) {
        Log.d("websocket","receive: "+message);
        Message msg = new Message();
        msg.obj = message;
        handler.sendMessage(msg);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        Log.d("websocket","Connection close by "+(remote?"remote peer":"us") +" at "+new Date(System.currentTimeMillis()));
    }

    @Override
    public void onError(Exception ex) {
        ex.printStackTrace();
    }
}



#####客户端建立链接(MainActivity.java)

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import org.java_websocket.drafts.Draft_17;

import java.net.URI;
import java.net.URISyntaxException;

import site.hackway.www.androidsite.websocket.SiteWebsocket;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        textView = (TextView) findViewById(R.id.txvw);
        SiteWebsocket siteWebsocket = null;
        try {
            siteWebsocket = new SiteWebsocket(new URI("ws://192.168.1.103:8080/sanguo/websocket"),new Draft_17(),textView);
            siteWebsocket.connectBlocking();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        /*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }

        });*/
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

客户端代码编写完毕,启动模拟器(注意客户端服务端需处于统一局域网)

输入图片说明

出现 用户名:LSH 说明连接成功

接着测试服务端向客户端发送消息 通过浏览器访问 http://ip:port/your project name/socket.do?uid=1

输入图片说明

服务端推送信息成功

服务端maven依赖,(其中spring的版本需要大于4)

    <properties>
		<spring.version>4.2.4.RELEASE</spring.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${spring.version}</version>
		</dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
            <version>${spring.version}</version>
        </dependency>
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.20</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.1.0</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.1.0</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.1.0</version>
		</dependency>

		<!-- logback日志配置 -->
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.1.3</version>
		</dependency>
		<dependency>
			<groupId>org.logback-extensions</groupId>
			<artifactId>logback-ext-spring</artifactId>
			<version>0.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>1.7.12</version>
		</dependency>
	</dependencies>

© 著作权归作者所有

共有 人打赏支持
Hackway
粉丝 2
博文 7
码字总数 2711
作品 0
广州
程序员
私信 提问
加载中

评论(3)

k
klx502

引用来自“klx502”的评论

大神,那个ios的例子没在你下一遍看到啊13

引用来自“Hackway”的评论

不好意思最近比较忙,没时间整理!
大神,我Android端传过来的参数都是乱码,我是用maven搭建的。请问怎么解决啊?
Hackway
Hackway

引用来自“klx502”的评论

大神,那个ios的例子没在你下一遍看到啊13
不好意思最近比较忙,没时间整理!
k
klx502
大神,那个ios的例子没在你下一遍看到啊13
为Phonegap Android平台增加websocket支持,使默认成为socket.io首选通

为Phonegap Android平台增加websocket支持,使默认成为socket.io首选通道选择 广而告之 使用socket.io作为跨浏览器平台的实时推送首选,经测试在各个主流浏览器上测试都确实具有良好的下实时...

james_laughing
2014/12/17
0
2
通过Websocket与gRPC交互 | gRPC双向数据流的交互控制系列(2)

在本系列第一篇文章《gRPC双向数据流的交互控制系列(1).初步实现》(https://www.jianshu.com/p/5158d6686769)中,我们完成了通过控制台进行gRPC双向数据流交互控制的实验。但是只是用控制台交...

阿狸不歌
07/26
0
0
WebSocket 是什么原理?为什么可以实现持久连接?

作者:腾讯云技术社区 众所周知,Web应用的通信过程通常是客户端通过浏览器发出一个请求,服务器端接收请求后进行处理并返回结果给客户端,客户端浏览器将信息呈现。这种机制对于信息变化不是...

xiaogong1688
06/29
0
0
Ubuntu 下 Janus Server 搭建

--Ubuntu 下 Janus Server 搭建笔记 一 、简介 Janus是一个开源的,通过 C 语言实现了对 WebRTC 支持的 Gateway;Janus 自身实现得很简单,提供插件机制来支持不同的业务逻辑,配合官方自带...

RobertZhou
09/19
0
0
android上使用WebSocket问题

我在 android 上使用了 github 下面的这个模块来做 WebSocket 客户端 https://github.com/crossbario/autobahn-android 代码就用上面的例子,非常简单,没加其他的 测试时发现长时间(20分钟...

skq
2016/07/08
686
1

没有更多内容

加载失败,请刷新页面

加载更多

EOS docker开发环境

使用eos docker镜像是部署本地EOS开发环境的最轻松愉快的方法。使用官方提供的eos docker镜像,你可以快速建立一个eos开发环境,可以迅速启动开发节点和钱包服务器、创建账户、编写智能合约....

汇智网教程
今天
4
0
《唐史原来超有趣》的读后感优秀范文3700字

《唐史原来超有趣》的读后感优秀范文3700字: 作者:花若离。我今天分享的内容《唐史原来超有趣》这本书的读后感,我将这本书看了一遍之后就束之高阁了,不过里面的内容一直在在脑海中回放,...

原创小博客
今天
9
0
IC-CAD Methodology知识图谱

CAD (Computer Aided Design),计算机辅助设计,指利用计算机及其图形设备帮助设计人员进行设计工作,这个定义同样可以用来近似描述IC公司CAD工程师这个岗位的工作。 早期IC公司的CAD岗位最初...

李艳青1987
今天
12
0
CompletableFuture get方法一直阻塞或抛出TimeoutException

问题描述 最近刚刚上线的服务突然抛出大量的TimeoutException,查询后发现是使用了CompletableFuture,并且在执行future.get(5, TimeUnit.SECONDS);时抛出了TimeoutException异常,导致接口响...

xiaolyuh
今天
6
0
dubbo 搭建与使用

官网:http://dubbo.apache.org/en-us/ 一,安装监控中心(可以不安装) admin管理控制台,monitor监控中心 下载 bubbo ops 这个是新版的,需要node.js环境,我没有就用老版的了...

小兵胖胖
今天
13
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部