• 安卓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);
        }
    
    }
  • 相关阅读:
    中英文对照 —— 宗教
    十万个为什么 —— 冷知识
    十万个为什么 —— 冷知识
    OpenCV调试利器——Image Watch插件的安装和使用
    matlab 读写其他格式数据文件(excel)
    matlab 读写其他格式数据文件(excel)
    文学创作的艺术手法
    文学创作的艺术手法
    常用cl命令参数解释
    网站的栏目和目录结构规划方法
  • 原文地址:https://www.cnblogs.com/Ocean123123/p/13879134.html
Copyright © 2020-2023  润新知