Android中使用WebSocket

原文地址:http://blog.csdn.net/tangxl2008008/article/details/52421413


 WebSocket 是 HTML5 一种新的协议。它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯,它建立在 TCP 之上,同 HTTP 一样通过 TCP 来传输数据,但是它和 HTTP 最大不同是:

        Ø  WebSocket 是一种双向通信协议,在建立连接后,WebSocket 服务器和 Browser/Client Agent 都能主动的向对方发送或接收数据,就像 Socket 一样;

        Ø  WebSocket 需要类似 TCP 的客户端和服务器端通过握手连接,连接成功后才能相互通信。

 

        下面主要使用“JavaWebSocket”开源项目,实现Android端与服务器端消息互通。

       Ø  Java-WebSocket地址:https://github.com/TooTallNate/Java-WebSocket

       Ø  Java-WebSocket jar下载地址:http://download.csdn.net/download/dodod2012/9938563

 

1.  客户端实现

        使用JavaWebSocket实现,直接使用WebSocketClient即可,下面为主要代码,不是全部的完整代码:

//WebSocketClient 和 address
private WebSocketClient mWebSocketClient;
private String address = "ws://192.168.0.134:8889";


//初始化WebSocketClient
/**
 *
 * @throws URISyntaxException
 */
private void initSocketClient() throws URISyntaxException {
    if(mWebSocketClient == null) {
        mWebSocketClient = new WebSocketClient(new URI(address)) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
//连接成功
                showInfo("opened connection");
            }


            @Override
            public void onMessage(String s) {
//服务端消息
                showInfo("received:" + s);
            }


            @Override
            public void onClose(int i, String s, boolean remote) {
//连接断开,remote判定是客户端断开还是服务端断开
                showInfo("Connection closed by " + ( remote ? "remote peer" : "us" ) + ", info=" + s);
                //
                closeConnect();
            }


            @Override
            public void onError(Exception e) {
                showInfo("error:" + e);
            }
        };
    }
}


//连接
private void connect() {
    new Thread(){
        @Override
        public void run() {            
            mWebSocketClient.connect();
        }
    }.start();
}


//断开连接
private void closeConnect() {
    try {
        mWebSocketClient.close();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
    finally {
        mWebSocketClient = null;
    }
}


//发送消息
/**
 *
 */
private void sendMsg(String msg) {
    mWebSocketClient.send(msg);

2.  服务端实现

        服务器这块还是使用JavaWebSocket实现,实现WebSocketServer类,功能如下:

public class ChatServer extends WebSocketServer {
public ChatServer(InetSocketAddress address, int decoders) {
   super(address, decoders);
    }


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

public ChatServer(int port) {
   this(new InetSocketAddress(port));
    }


@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
final String info = conn.getRemoteSocketAddress().getAddress().getHostAddress() + " 断开!,reason=" + reason;
showInfo(info);

send2All(info);
showInfo("发送:" + info);
}


@Override
public void onError(WebSocket conn, Exception e) {
final String info = conn.getRemoteSocketAddress().getAddress().getHostAddress() + ", error=>" + e;

showInfo(info);
}


@Override
public void onMessage(WebSocket conn, String msg) {
final String info = conn.getRemoteSocketAddress().getAddress().getHostAddress() + ", msg=>" + msg;
showInfo("读取:" + info);
send2All(info);
showInfo("发送:" + info);
}


@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
final String info = conn.getRemoteSocketAddress().getAddress().getHostAddress() + "接入!";
showInfo(info);

send2All(info);
showInfo("发送:" + info);
}


/**
* @param info
*/
protected void send2All(String info) {
Iterator<WebSocket> interator = connections().iterator();
while(interator.hasNext()) {
interator.next().send(info);
}
}

protected void showInfo(String info) {
System.out.println(info);
}

public static void main(String[] args) throws IOException {
   ChatServer server = new ChatServer(8889);
   server.start();
   
   System.out.println("服务端连接已开启,等待客户端接入,端口号:" + server.getPort());   
   BufferedReader websocketIn = new BufferedReader(new InputStreamReader(System.in));
   while(true) {
    String strIn = websocketIn.readLine();
    server.send2All(strIn);
    server.showInfo("获取:" + strIn);
   }
    }
}

Android使用WebSocketClient需要以下步骤: 1. 在`build.gradle`文件添加WebSocket依赖: ```groovy implementation 'org.java-websocket:Java-WebSocket:1.5.1' ``` 2. 创建一个WebSocketClient类来处理WebSocket连接和消息的收发: ```java import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import java.net.URI; import java.net.URISyntaxException; public class MyWebSocketClient extends WebSocketClient { public MyWebSocketClient(String url) throws URISyntaxException { super(new URI(url)); } @Override public void onOpen(ServerHandshake handshakedata) { // 连接打开时的处理逻辑 } @Override public void onMessage(String message) { // 接收到消息时的处理逻辑 } @Override public void onClose(int code, String reason, boolean remote) { // 连接关闭时的处理逻辑 } @Override public void onError(Exception ex) { // 出现错误时的处理逻辑 } } ``` 3. 在需要使用WebSocket的地方创建并连接WebSocketClient: ```java try { MyWebSocketClient client = new MyWebSocketClient("ws://example.com/socket"); client.connect(); } catch (URISyntaxException e) { e.printStackTrace(); } ``` 4. 可以使用以下方法发送和关闭连接: ```java client.send("Hello, server!"); // 发送消息给服务器 client.close(); // 关闭连接 ``` 以上是基本的使用方法,你可以根据实际需求在`onOpen`、`onMessage`、`onClose`和`onError`方法添加自己的逻辑来处理连接和消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值