Android WebSocket 长连接推送

  • Post author:
  • Post category:其他


本地局网传送


第一步客户端


导入WebSocket jar包


implementation ‘org.java-websocket:Java-WebSocket:1.3.0’

private WebSocketClient mSocketClient;

@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

ButterKnife.bind(this);

init();

handler = new Handler() {


@Override

public void handleMessage(Message msg) {


super.handleMessage(msg);

wedTv.setText(wedTv.getText() + “\n” + msg.obj);

}

};

}

private void init() {


new Thread() {


@Override

public void run() {


try {


Log.i(“WebSocketClient_”, “run_1111111”);

mSocketClient = new WebSocketClient(new URI(“ws://192.168.1.54:5478 “), new Draft_10()) {


@Override

public void onOpen(ServerHandshake handshakedata) {//打开通道

Log.i(“WebSocketClient_”, “onOpen_ 22222=”+handshakedata);

handler.obtainMessage(0, handshakedata).sendToTarget();

}

@Override

public void onMessage(String message) {//接受服务器信息

Log.i(“WebSocketClient_”, “onMessage_ 3333=”+message);

handler.obtainMessage(0, message).sendToTarget();

}

@Override

public void onClose(int code, String reason, boolean remote) {//通道关闭

Log.i(“WebSocketClient_”, “onClose_ 44444=”+reason);

handler.obtainMessage(0, reason).sendToTarget();

}

@Override

public void onError(Exception ex) {


Log.i(“WebSocketClient_”, “onError_ 5554″+ex);

}

};

mSocketClient.connect();

} catch (Exception e) {


e.printStackTrace();

}

}

}.start();

}

@OnClick({R.id.wed_bu})

public void onViewClicked(View view) {


switch (view.getId()) {

case R.id.wed_bu:

if (mSocketClient != null){


String str =  wedEt.getText().toString();

mSocketClient.send(str);

}

break;

}

@Override

protected void onDestroy() {


super.onDestroy();

if (mSocketClient != null){


mSocketClient.close();

}

}


客户端长连接发数据服务器接受,效果图


服务端接受客户端数据效果图




第二步服务端代码,服务器接受客户端数据,和服务器发送数据给客户端

导入包 implementation ‘org.java-websocket:Java-WebSocket:1.3.0’

private static int PORT = 5478;
//telnet localhost  建立服务器
//ipconfig获取主机IP
//ping 拼接IP
public static void main(String[] arges) throws IOException  {

    /*-------WebSocket-------*/
    MWebSocketService socketServer = new MWebSocketService(PORT);
    socketServer.start();

    try {
        String ip = InetAddress.getLocalHost().getHostAddress();
        int port = socketServer.getPort();
        System.out.print(String.format("服务已启动: %s:%d", ip, port));
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    InputStreamReader in = new InputStreamReader(System.in);
    BufferedReader reader = new BufferedReader(in);

    while (true){
        try {
            String msg = reader.readLine();
            socketServer.senToll(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

创建一个MWebSocketService类

public class MWebSocketService  extends WebSocketServer {


    public MWebSocketService(int port) throws UnknownHostException {
        super(new InetSocketAddress(port));

    }
    public MWebSocketService(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        String address = webSocket.getRemoteSocketAddress().getAddress().getHostAddress();
        String message = String.format("(%s) <进入房间!>", address);
        senToll(message);
        System.out.println(message);


    }

    @Override
    public void onClose(WebSocket webSocket, int code, String reason, boolean remote) {
        String address = webSocket.getRemoteSocketAddress().getAddress().getHostAddress();
        String message = String.format("(%s) <退出房间!>", address);
        senToll(message);
        System.out.println(message);

    }
    /**
     * 收到客户端消息后调用的方法
     *
     * @param //message 客户端发送过来的消息
     * @param
     */

    @Override
    public void onMessage(WebSocket webSocket, String s) {
        //服务端接收到消息
        String address = webSocket.getRemoteSocketAddress().getAddress().getHostAddress();
        String message = String.format("(%s) %s ",address,s);

        //将消息发送给所有客户端
        senToll("我是能能");//senToll方法是发数据给客户端
        System.out.print(message);

    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {
        if (null != webSocket){
            webSocket.close();
        }
        e.printStackTrace();

    }
    public void senToll(String message){
        // 获取所有连接的客户端
        Collection<WebSocket> connections = connections();
        //将消息发送给每一个客户端
        for (WebSocket client : connections ){
            client.send(message);
        }

    }
}


服务器长连接发数据给客户端接受效果图



版权声明:本文为yineng7758258原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。