菜鸟从零开始初始WebSocket

来源:互联网 发布:python下载matplotlib 编辑:程序博客网 时间:2024/05/29 16:45

1. Android端

 需要一个新的 Project, (用的Android studio)

需要一个WebSocket 库, 经过我的超强度娘功能, 找到一家 https://github.com/TooTallNate/Java-WebSocket (其实还有其他的很多, 可是因为懒得另外找源代码了, 就这个先试试), 另外, 找个基于Gradle的也不容易。。。


怎么把两个Gradle 放在同一个项目里面, 在其中一个引用另外一个作为Library




然后就等着了, 编译成功以后再代码里面就可以用lib project里面的函数了:


public class TestClient extends WebSocketClient {

public TestClient(URI serverUri , Draft draft ) {
super( serverUri, draft );
}

public TestClient( URI serverURI ) {
super( serverURI );
}

@Override
public void onOpen( ServerHandshake handshakedata ) {
System.out.println( "opened connection" );
// if you plan to refuse connection based on ip or httpfields overload: onWebsocketHandshakeReceivedAsClient
}

@Override
public void onMessage( String message ) {
System.out.println( "received: " + message );
}

@Override
public void onFragment( Framedata fragment ) {
System.out.println( "received fragment: " + new String( fragment.getPayloadData().array() ) );
}

@Override
public void onClose( int code, String reason, boolean remote ) {
// The codecodes are documented in class org.java_websocket.framing.CloseFrame
System.out.println( "Connection closed by " + ( remote ? "remote peer" : "us" ) );
}

@Override
public void onError( Exception ex ) {
ex.printStackTrace();
// if the error is fatal then onClose will be called additionally
}
}


再用一个按钮什么的来触发连接: URI uri = null;
try {
uri = new URI(URL);
}catch (URISyntaxException e){

}
client = new TestClient( uri );
client.connect();



然后客户端应该就这样了


下一篇做服务器端


0 0
原创粉丝点击