OkHttp3 websocket

举报
风吹稻花香 发表于 2021/06/05 22:52:48 2021/06/05
【摘要】 使用OkHttp3之Websocket实现长连接 这个发图片也没成功,发字符是可以的。 首先在在build.gradle中添加对Okhttp的支持 compile 'com.squareup.okhttp3:okhttp:3.8.1' compile 'com.squareup.okhttp3:mockwebserver:3.8.1' 布局文件 <?xml ...

使用OkHttp3之Websocket实现长连接

这个发图片也没成功,发字符是可以的。

首先在在build.gradle中添加对Okhttp的支持

compile 'com.squareup.okhttp3:okhttp:3.8.1'

compile 'com.squareup.okhttp3:mockwebserver:3.8.1'

布局文件

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/activity_main"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.yinzhendong.websocket.MainActivity">

 

<ScrollView

android:layout_width="match_parent"

android:layout_height="wrap_content">

<LinearLayout

android:layout_marginLeft="20dp"

android:layout_marginRight="20dp"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:gravity="center_horizontal"

android:orientation="vertical">

<Button

android:id="@+id/start"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="10dp"

android:text="连接"

android:textSize="17sp"/>

<TextView

android:id="@+id/output"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginTop="10dp"

android:textSize="16sp"/>

</LinearLayout>

</ScrollView>

</RelativeLayout>

MainActivity.java


  
  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener{
  2. private Button btnStart;
  3. private TextView tvOutput;
  4. private WebSocket mSocket;
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_main);
  9. btnStart = (Button) findViewById(R.id.start);
  10. tvOutput = (TextView) findViewById(R.id.output);
  11. btnStart.setOnClickListener(this);
  12. }
  13. private void start() {
  14. OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
  15. .readTimeout(3, TimeUnit.SECONDS)//设置读取超时时间
  16. .writeTimeout(3, TimeUnit.SECONDS)//设置写的超时时间
  17. .connectTimeout(3, TimeUnit.SECONDS)//设置连接超时时间
  18. .build();
  19. Request request = new Request.Builder().url("ws://echo.websocket.org").build();
  20. EchoWebSocketListener socketListener = new EchoWebSocketListener();
  21. mOkHttpClient.newWebSocket(request, socketListener);
  22. mOkHttpClient.dispatcher().executorService().shutdown();
  23. }
  24. /**
  25. * @param v The view that was clicked.
  26. */
  27. @Override
  28. public void onClick(View v) {
  29. switch (v.getId()) {
  30. case R.id.start://开始连接
  31. start();
  32. break;
  33. }
  34. }
  35. private final class EchoWebSocketListener extends WebSocketListener {
  36. @Override
  37. public void onOpen(WebSocket webSocket, Response response) {
  38. super.onOpen(webSocket, response);
  39. mSocket = webSocket;
  40. String openid = "1";
  41. //连接成功后,发送登录信息
  42. String message = "{\"type\":\"login\",\"user_id\":\""+openid+"\"}";
  43. mSocket.send(message);
  44. output("连接成功!");
  45. }
  46. @Override
  47. public void onMessage(WebSocket webSocket, ByteString bytes) {
  48. super.onMessage(webSocket, bytes);
  49. output("receive bytes:" + bytes.hex());
  50. }
  51. @Override
  52. public void onMessage(WebSocket webSocket, String text) {
  53. super.onMessage(webSocket, text);
  54. output("receive text:" + text);
  55. //收到服务器端发送来的信息后,每隔25秒发送一次心跳包
  56. final String message = "{\"type\":\"heartbeat\",\"user_id\":\"heartbeat\"}";
  57. Timer timer = new Timer();
  58. timer.schedule(new TimerTask() {
  59. @Override
  60. public void run() {
  61. mSocket.send(message);
  62. }
  63. },25000);
  64. }
  65. @Override
  66. public void onClosed(WebSocket webSocket, int code, String reason) {
  67. super.onClosed(webSocket, code, reason);
  68. output("closed:" + reason);
  69. }
  70. @Override
  71. public void onClosing(WebSocket webSocket, int code, String reason) {
  72. super.onClosing(webSocket, code, reason);
  73. output("closing:" + reason);
  74. }
  75. @Override
  76. public void onFailure(WebSocket webSocket, Throwable t, Response response) {
  77. super.onFailure(webSocket, t, response);
  78. output("failure:" + t.getMessage());
  79. }
  80. }
  81. private void output(final String text) {
  82. runOnUiThread(new Runnable() {
  83. @Override
  84. public void run() {
  85. tvOutput.setText(tvOutput.getText().toString() + "\n\n" + text);
  86. }
  87. });
  88. }
  89. }

 

文章来源: blog.csdn.net,作者:网奇,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/jacke121/article/details/103594260

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。