文档章节

websocket服务端,android客户端示例

Hackway
 Hackway
发布于 2016/03/02 01:55
字数 1184
阅读 374
收藏 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
Ubuntu 下 Janus Server 搭建

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

RobertZhou
09/19
0
0
WebSocket 是什么原理?为什么可以实现持久连接?

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

xiaogong1688
06/29
0
0
android内置浏览器不支持websocket的解决方法

为了实现移动客户端实时通信,拟采用安卓webview内嵌html实现方式开发app,通信则采用最新的html5新特性websocket实现。经测试,android4.0以下内置浏览器都不支持websocket特性。经过googl...

chape
2014/03/01
0
2

没有更多内容

加载失败,请刷新页面

加载更多

读书(附电子书)|小狗钱钱之白色的拉布拉多

关注公众号,在公众号中回复“小狗钱钱”可免费获得电子书。 一、背景 之前写了一篇文章 《小狗钱钱》 理财小白应该读的一本书,那时候我才看那本书,现在看了一大半了,发现这本书确实不错,...

tiankonguse
32分钟前
0
0
Permissions 0777 for ‘***’ are too open

异常显示: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: UNPROTECTED PRIVATE KEY FILE! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ......

李玉长
34分钟前
0
0
区块链10年了,还未落地,它失败了吗?

导读 几乎每个人,甚至是对通证持怀疑态度的人,都对区块链的技术有积极的看法,因为它有可能改变世界。然而,区块链技术问世已经10年了,我们仍然没有真正的用上区块链技术。 几乎每个人,甚...

问题终结者
今天
2
0
20180921 su与sudo命令、限制root用户通过ssh远程登录

su 命令 用户切换。 su # 切换到root用户su username # 切换到username用户# su 后面加-时,会初始化当前用户的各种环境su - username # 指定用户执行某些命令 su - -c "touch /tm...

野雪球
今天
2
0
Windows 下双 Python 开发环境配置

Windows 下双 Python 开发环境配置作者:老农民(刘启华)QQ: 46715422Email: 46715422@qq.com微信: 46715422 本人曾经在 Windows 下被两个版本环境折腾够呛,现在总结两个 Python...

新疆老农民
昨天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部