a端发送Message
WebSocket mConnecttion=new WebSocketConnection();
mConnecttion.connect(wsUri, new WebSocketConnectionHandler(){
@Override
public void onOpen() {
Log.d("MessageSender.start.open", "open");
mConnecttion.sendTextMessage(msg);
super.onOpen();
}
@Override
public void onClose(int code, String reason) {
Log.d("MessageSender.start.close", "close");
super.onClose(code, reason);
}
@Override
public void onTextMessage(String payload) {
Log.d("MessageSender.start.textMessage", "textMessage");
super.onTextMessage(payload);
}
});
wsUrl的格式是:ws://192.168.8.29:8088/
b端接受Message
public class WebSocket extends NanoWebSocketServer{
public WebSocket(int port) {
super(port);
}
public WebSocket(String hostname, int port) {
super(hostname, port);
}
@Override
public WebSocket openWebSocket(IHTTPSession handshake) {
Log.d("WebSocket .openWebSocket", "openWebSocket");
return super.openWebSocket(handshake);
}
//受到消息
@Override
protected void onFrameReceived(WebSocketFrame webSocket) {
webSocket.getTextPayload();
Log.d("WebSocket .onFrameReceived", webSocket.getTextPayload());
super.onFrameReceived(webSocket);
}
@Override
public void onSendFrame(WebSocketFrame webSocket) {
Log.d("WebSocket .onSendFrame", "onSendFrame");
super.onSendFrame(webSocket);
}
@Override
protected void onClose(WebSocket arg0, CloseCode arg1, String arg2,
boolean arg3) {
Log.d("WebSocket .onClose", "onClose");
}
@Override
protected void onException(WebSocket arg0, IOException arg1) {
Log.d("WebSocket .onException", "onException");
arg1.printStackTrace();
}
@Override
protected void onMessage(WebSocket arg0, WebSocketFrame arg1) {
Log.d("WebSocket .onMessage", "onMessage");
}
@Override
protected void onPong(WebSocket arg0, WebSocketFrame arg1) {
Log.d("WebSocket .onPong", "onPong");
}
}
a端可以发送自己的ip和端口信息到b端,同时在a端用NanoHTTPD实现小型的服务器,然后b端可以通过http请求访问a端,实现通信。
NanoHTTPD服务:
public class WebService extends NanoHTTPD{
public WebService(int port) {
super(port);
}
public WebService(String hostname, int port) {
super(hostname, port);
}
@Override
public Response serve(IHTTPSession session) {
Log.d("WebService.session.url",session.getUri());
if(session.getUri().equals("http://192.168.8.250:9000/image")){
try {
InputStream input=new StringBufferInputStream("我发的就是这么没意义!");
return newChunkedResponse(Status.OK,"image",input);
} catch (Exception e) {
e.printStackTrace();
}
}
return super.serve(session);
}
}
b端的Http请求: