zoukankan      html  css  js  c++  java
  • 安卓WebSocket使用

    引入jar包:

       implementation "org.java-websocket:Java-WebSocket:1.4.0"
    implementation "org.slf4j:slf4j-nop:1.7.25"


    websocket相对于socket是页面和页面进行通信,比socket要好用点

    先看服务端start之后就一直监听客户端的连接,可以连接多个客户端生成多个Websocket实例

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate( savedInstanceState );
            setContentView( R.layout.activity_main );
    
    
    
    
        }
    
    
        public static void main(String[] args) throws IOException {
    
            final ChatServer chatServer = new ChatServer( 9999 );
    
            chatServer.start();
    
        }
    public class ChatServer extends WebSocketServer {
    
        private WebSocket webSocket;
    
        public ChatServer(int port){
            super(new InetSocketAddress(port));
        }
    
        @Override
        public void onOpen(WebSocket conn, ClientHandshake handshake) {
            System.out.println("服务端打开"+conn.getLocalSocketAddress().getAddress().getHostAddress() );
    
            webSocket=conn;
        }
    
        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            System.out.println("服务端关闭");
        }
    
        @Override
        public void onMessage(WebSocket conn, String message) {
            System.out.println("服务端收到消息");
            conn.send( "服务端发送的消息" );
            webSocket=conn;
        }
    
        @Override
        public void onError(WebSocket conn, Exception ex) {
    
            System.out.println("服务端错误"+ex.getMessage() );
        }
    
        @Override
        public void onStart() {
    
            System.out.println("服务端开始");
        }
    
        public void sendMsg(String content){
            if(webSocket!=null) {
                webSocket.send(content);
            }
            else {
                System.out.println("请先初始化" );
    
            }
        }
    }

    如果有客户端连接会执行onopen方法

    然后是客户端:

    public class MainActivity3 extends AppCompatActivity {
        private ChatClient instance;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate( savedInstanceState );
            setContentView( R.layout.activity_main3 );
            URI uri = URI.create( "ws://xx.xx.x.xx:9999" );
             instance = ChatClient.getInstance( uri );
    
            new Thread() {
                @Override
                public void run() {
                    try {
                        //connectBlocking多出一个等待操作,会先连接再发送,否则未连接发送会报错
                        instance.connectBlocking();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            findViewById( R.id.main3button1 ).setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    instance.send( "是的咖啡机" );
                }
            } );
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            try {
                if (null != instance) {
                    instance.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                instance = null;
            }
        }
    }
    public class ChatClient extends WebSocketClient {
    
        private static volatile ChatClient client = null;
        private Handler mHandler;
    
        public ChatClient(URI uri) {
            super(uri);
    
        }
    
        /**
         * DCL
         *
         * @param uri
         * @return
         */
        public static ChatClient getInstance(URI uri) {
            if (client == null) {
                synchronized (ChatClient.class) {
                    if (client == null) {
                        client = new ChatClient(uri);
                    }
                }
            }
            return client;
        }
    
    
        @Override
        public void onOpen(ServerHandshake handshakedata) {
    
            System.out.println("客户端打开"+handshakedata.getHttpStatusMessage());
    
        }
    
        @Override
        public void onMessage(String message) {
            System.out.println("收到信息"+message);
    
        }
    
        @Override
        public void onClose(int code, String reason, boolean remote) {
            System.out.println("客户端关闭");
    
        }
    
        @Override
        public void onError(Exception ex) {
            System.out.println("错误"+ex);
        }
    
    }
  • 相关阅读:
    UVA 12657 Boxes in a Line 双向链表模拟
    C语言单片和C#语言服务器端DES及3DES加密的实现
    关于TcpClient,Socket连接超时的几种处理方法
    拿来参考的学习计划
    faire la course
    今日法语2
    炸鱼
    今日法语
    今日疑问
    下周想做的菜
  • 原文地址:https://www.cnblogs.com/Ocean123123/p/13879134.html
Copyright © 2011-2022 走看看