I need help with connect on android to my WebSocket server based on Spring boot. Source code of this server I have taken https://spring.io/guides/gs/messaging-stomp-websocket/
Everything works fine on server and browser client on this sample,
but if I use StompClient (https://github.com/NaikSoftware/StompProtocolAndroid) to connect on my socket I am getting mStompClient.isConnected() == false and conand mStompClient.send(...) doesn't send anything (?).
After few minutes socketweb server closes the connection and I get in my log: '~~ Stomp connection closed'.
Web server locates on Heroku cloud system.
There is my connecting code from android activity:
private StompClient mStompClient;
private void connectStomp(){
mStompClient = Stomp.over(WebSocket.class, "wss://myserver/gs-guide-websocket");
mStompClient.topic("/topic/greetings").subscribe(new Action1<StompMessage>() {
#Override
public void call(StompMessage stompMessage) {
Log.w(TAG, "== "+stompMessage.getPayload());
}
});
mStompClient.connect();
mStompClient.lifecycle().subscribe(new Action1<LifecycleEvent>() {
#Override
public void call(LifecycleEvent lifecycleEvent) {
switch (lifecycleEvent.getType()) {
case OPENED:
Log.w(TAG, "~~ Stomp connection opened");
break;
case ERROR:
Log.e(TAG, "~~ Error", lifecycleEvent.getException());
break;
case CLOSED:
Log.w(TAG, "~~ Stomp connection closed "+lifecycleEvent.getMessage());
break;
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
connectStomp();
}
// Send test request to server
public void onSend(View view){
Log.w(TAG,"onSend: click");
mStompClient.send("/app/hello","Test").subscribe(new Observer<Void>() {
#Override
public void onCompleted() {
Log.w(TAG, "~~~~ onCompleted");
}
#Override
public void onError(Throwable e) {
Log.w(TAG, "~~~~ onCompleted "+e.getMessage());
}
#Override
public void onNext(Void aVoid) {
Log.w(TAG, "~~~~ onNext ");
}
});
if (mStompClient.isConnected()){
mStompClient.send("/app/hello","test msg").subscribe();
Log.w("aaaa : ","onCreate: connected");
}
}
It would be my mistake but if I connect to my server socket with spring boot WebSocketStompClient everithing works fine:
private SockJsClient sockJsClient;
private WebSocketStompClient stompClient;
private final WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
#Before
public void setup() {
List<Transport> transports = new ArrayList<>();
transports.add(new WebSocketTransport(new StandardWebSocketClient()));
this.sockJsClient = new SockJsClient(transports);
this.stompClient = new WebSocketStompClient(sockJsClient);
this.stompClient.setMessageConverter(new MappingJackson2MessageConverter());
}
#Test
public void getGreeting() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> failure = new AtomicReference<>();
StompSessionHandler handler = new TestSessionHandler(failure) {
#Override
public void afterConnected(final StompSession session, StompHeaders connectedHeaders) {
session.subscribe("/topic/greetings", new StompFrameHandler() {
#Override
public Type getPayloadType(StompHeaders headers) {
return Greeting.class;
}
#Override
public void handleFrame(StompHeaders headers, Object payload) {
Greeting greeting = (Greeting) payload;
try {
System.out.println(greeting.getContent());
assertEquals("Hello, Spring!", greeting.getContent());
} catch (Throwable t) {
System.out.println(t.getMessage());
failure.set(t);
} finally {
session.disconnect();
latch.countDown();
}
}
});
try {
session.send("/app/hello", "Test");
} catch (Throwable t) {
failure.set(t);
latch.countDown();
}
}
};
this.stompClient.connect("wss://myserver/gs-guide-websocket", this.headers, handler, 443);
if (latch.await(10, TimeUnit.SECONDS)) {
if (failure.get() != null) {
throw new AssertionError("", failure.get());
}
}
else {
fail("Greeting not received");
}
}
private class TestSessionHandler extends StompSessionHandlerAdapter {
private final AtomicReference<Throwable> failure;
public TestSessionHandler(AtomicReference<Throwable> failure) {
this.failure = failure;
}
#Override
public void handleFrame(StompHeaders headers, Object payload) {
this.failure.set(new Exception(headers.toString()));
}
#Override
public void handleException(StompSession s, StompCommand c, StompHeaders h, byte[] p, Throwable ex) {
this.failure.set(ex);
}
Any ideas? Thanks a lot!
I used the same Library in order to connect with Stomp based web socket. There were some configurations on the server side. On the android side, I was using URL as starting with "ws://" and ending with "websocket" like "ws://" + SERVER_URL + "/websocket".
See this answer for server side https://stackoverflow.com/a/41751897/5392825
Related
So, I have the following code working for connecting to the socket.
But I am trying to invoke (or listen to) OnText event from the WebSocketListener, to get the data received from websocket.
Any help is much appreciated.
public class WebSocketListener implements WebSocket.Listener {
#Override
public void onOpen(WebSocket webSocket) {
webSocket.request(1);
_logger.trace("Connected to WebSocket.");
_logger.debug("WebSocket Listener has been opened for requests.");
WebSocket.Listener.super.onOpen(webSocket);
}
#Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
_logger.trace("onText: ", data);
webSocket.request(1);
_logger.info("onText() completed.");
JSONObject response = new JSONObject(data.toString());
//
// How to return it to the class requesting/listening on it?
//
return new CompletableFuture().newIncompleteFuture().thenAccept(System.out::println);
//return WebSocket.Listener.super.onText(webSocket, data, last);
}
#Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
_logger.debug("WebSocket Listener has been closed with statusCode: {}, and cause: {}",statusCode, reason);
webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "ok");
return new CompletableFuture<Void>();
//return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
#Override
public void onError(WebSocket webSocket, Throwable error) {
_logger.error("A " + error.getCause() + " exception was thrown.");
_logger.error("Message: " + error.getLocalizedMessage());
webSocket.abort();
}
#Override
public CompletionStage<?> onPing(WebSocket webSocket, ByteBuffer message){
webSocket.request(1);
_logger.trace("Ping: Client ---> Server");
_logger.trace(message.asCharBuffer().toString());
_logger.trace("Ping completed.");
// return new CompletableFuture().completedFuture​("Ping completed.").thenAccept(System.out::println);
return new CompletableFuture().newIncompleteFuture().thenAccept(System.out::println);
}
#Override
public CompletionStage<?> onPong(WebSocket webSocket, ByteBuffer message){
webSocket.request(1);
_logger.trace("Pong: Client ---> Server");
_logger.trace(message.asCharBuffer().toString());
//return new CompletableFuture().completedFuture​("Pong completed.").thenAccept(System.out::println);
_logger.trace("Pong completed.");
return new CompletableFuture().newIncompleteFuture().thenAccept(System.out::println);
}
}
Following is the WebSocketClient that would handle creating the socket, connect, reconnect, login, logout, getSession from the WebSocket API.
private static CompletableFuture<WebSocket> _websocket_cf;
private static WebSocket _webSocket;
public WebSocketClient() {
try {
_secure = true;
WebSocketListener wsListener = new WebSocketListener();
TrustingHttpClient client = HttpUtil.getDefaultHttpClient().addTrustedHost(10.200.60.15);
_websocket_cf = client
.newWebSocketBuilder()
.buildAsync(URI.create("wss://10.200.60.15/remoteapi"), wsListener); //
_webSocket = _websocket_cf.join();
_logger.info("WebSocket created.");
}
catch (Exception ex) {
_logger.error("Failed to create WebSocket. ", ex);
}
}
public WebSocket getWebSocket() { return _webSocket; }
.....
}
No, I would like to get the data received from OnText event, here in this method.
Public class SocketExample {
private WebSocketClient _wsc;
private void getData(){
_wsc = new WebSocketClient();
WebSocket ws = _wsc.getWebSocket();
// get the data received in OnText event here ?
}
}
Thanks for your help.
I'm learning Netty and prototyping a simple app which sends an object over TCP. My issue is that when I call Channel.write from the server side with my message, it doesn't seem to reach the handlers in the pipeline. When I send a message from client to server, it works as expected.
Here's the code.
The server:
public class Main {
private int serverPort;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private ServerBootstrap boot;
private ChannelFuture future;
private SomeDataChannelDuplexHandler duplex;
private Channel ch;
public Main(int serverPort) {
this.serverPort = serverPort;
}
public void initialise() {
boot = new ServerBootstrap();
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
boot.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(0, 0, 2));
// Inbound
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 0));
ch.pipeline().addLast(new SomeDataDecoder());
// Outbound
ch.pipeline().addLast(new LengthFieldPrepender(2));
ch.pipeline().addLast(new SomeDataEncoder());
// In-Out
ch.pipeline().addLast(new SomeDataChannelDuplexHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
}
public void sendMessage() {
SomeData fd = new SomeData("hello", "localhost", 1234);
ChannelFuture future = ch.writeAndFlush(fd);
future.addListener(new ChannelFutureListener() {
#Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
System.out.println("send error: " + future.cause().toString());
} else {
System.out.println("send message ok");
}
}
});
}
public void startServer(){
try {
future = boot.bind(serverPort)
.sync()
.addListener(new ChannelFutureListener() {
#Override
public void operationComplete(ChannelFuture future) throws Exception {
ch = future.channel();
}
});
} catch (InterruptedException e) {
// log failure
}
}
public void stopServer() {
workerGroup.shutdownGracefully()
.addListener(e -> System.out.println("workerGroup shutdown"));
bossGroup.shutdownGracefully()
.addListener(e -> System.out.println("bossGroup shutdown"));
}
public static void main(String[] args) throws InterruptedException {
Main m = new Main(5000);
m.initialise();
m.startServer();
final Scanner scanner = new Scanner(System.in);
System.out.println("running.");
while (true) {
final String input = scanner.nextLine();
if ("q".equals(input.trim())) {
break;
} else {
m.sendMessage();
}
}
scanner.close();
m.stopServer();
}
}
The duplex channel handler:
public class SomeDataChannelDuplexHandler extends ChannelDuplexHandler {
#Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("duplex channel active");
ctx.fireChannelActive();
}
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("duplex channelRead");
if (msg instanceof SomeData) {
SomeData sd = (SomeData) msg;
System.out.println("received: " + sd);
} else {
System.out.println("some other object");
}
ctx.fireChannelRead(msg);
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
#Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.ALL_IDLE) { // idle for no read and write
System.out.println("idle: " + event.state());
}
}
}
}
And finally the encoder (the decoder is similar):
public class SomeDataEncoder extends MessageToByteEncoder<SomeData> {
#Override
protected void encode(ChannelHandlerContext ctx, SomeData msg, ByteBuf out) throws Exception {
System.out.println("in encoder, msg = " + msg);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(msg.getName());
oos.writeObject(msg.getIp());
oos.writeInt(msg.getPort());
oos.close();
byte[] serialized = bos.toByteArray();
int size = serialized.length;
ByteBuf encoded = ctx.alloc().buffer(size);
encoded.writeBytes(bos.toByteArray());
out.writeBytes(encoded);
}
}
The client side:
public class Client {
String host = "10.188.36.66";
int port = 5000;
EventLoopGroup workerGroup = new NioEventLoopGroup();
ChannelFuture f;
private Channel ch;
public Client() {
}
public void startClient() throws InterruptedException {
Bootstrap boot = new Bootstrap();
boot.group(workerGroup);
boot.channel(NioSocketChannel.class);
boot.option(ChannelOption.SO_KEEPALIVE, true);
boot.handler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
// Inbound
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 0));
ch.pipeline().addLast(new SomeDataDecoder());
// Outbound
ch.pipeline().addLast(new LengthFieldPrepender(2));
ch.pipeline().addLast(new SomeDataEncoder());
// Handler
ch.pipeline().addLast(new SomeDataHandler());
}
});
// Start the client
f = boot.connect(host, port).sync();
f.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
System.out.println("connected to server");
ch = f.channel();
}
});
}
public void stopClient() {
workerGroup.shutdownGracefully();
}
private void writeMessage(String input) {
SomeData data = new SomeData("client", "localhost", 3333);
ChannelFuture fut = ch.writeAndFlush(data);
fut.addListener(new ChannelFutureListener() {
#Override
public void operationComplete(ChannelFuture future) throws Exception {
System.out.println("send message");
}
});
}
public static void main(String[] args) throws InterruptedException {
Client client = new Client();
client.startClient();
System.out.println("running.\n\n");
final Scanner scanner = new Scanner(System.in);
while (true) {
final String input = scanner.nextLine();
if ("q".equals(input.trim())) {
break;
} else {
client.writeMessage(input);
}
}
scanner.close();
client.stopClient(); //call this at some point to shutdown the client
}
}
and the handler:
public class SomeDataHandler extends SimpleChannelInboundHandler<SomeData> {
private ChannelHandlerContext ctx;
#Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("connected");
this.ctx = ctx;
}
#Override
protected void channelRead0(ChannelHandlerContext ctx, SomeData msg) throws Exception {
System.out.println("got message: " + msg);
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.println("caught exception: " + cause.getMessage());
ctx.close();
}
}
When I send a message via the console on the server side, I get the output:
running.
duplex channel active
duplex read
idle: ALL_IDLE
idle: ALL_IDLE
send message ok
So it looks as though the message is sent but nothing is received on the client side.
When I do it from the client side I get (on the server console):
in decoder, numBytes in message = 31
duplex channelRead
received: SomeData [name=client, ip=localhost, port=3333]
which is what I expect.
So where's the problem? Is it something to do with using a ChannelDuplexHandler on the server side and a SimpleChannelInboundHandler on the client side? Is there something I need to call to kick the message down the pipeline?
UPDATE
I've added a check for future.isSuccess() in the server sendMessage method and I get
send error: java.lang.UnsupportedOperationException on the console.
(Posted on behalf of the OP).
For anyone who's interested, the problem was that I was trying to send the message on the server channel and not the normal channel. This post pointed me in the right direction.
Hi I am confused with the logic of implementing chatManagerListener interface inside a Service.
Below is my service code:
public class MyService3 extends Service {
ChatManager chatManager;
ChatManagerListener chatManagerListener;
AbstractXMPPConnection abstractXMPPConnection;
MyXmpp2 myXmpp2;
public MyService3() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("Myservice3:","Started");
abstractXMPPConnection = myXmpp2.getConnection();
abstractXMPPConnection.addConnectionListener(new ConnectionListener() {
#Override
public void connected(XMPPConnection connection) {
Log.d("XMPPConnection:","connected");
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
Log.d("XMPPConnection:","authenticated");
//Once authenticated start listening for messages
}
#Override
public void connectionClosed() {
Log.d("XMPPConnection:","connectionClosed");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("XMPPConnection:","connectionClosedOnError");
}
#Override
public void reconnectionSuccessful() {
Log.d("XMPPConnection:","reconnectionSuccessful");
}
#Override
public void reconnectingIn(int seconds) {
Log.d("XMPPConnection:","reconnectingIn");
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("XMPPConnection:","reconnectionFailed");
}
});
Log.d("isOnline:", myXmpp2.getConnection().isConnected() + "");
chatManager = ChatManager.getInstanceFor(abstractXMPPConnection);
chatManager.addChatListener(chatManagerListener);
chatManagerListener = new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
Log.d("Hello::","World");
//NOT WORKNIG
if(message.getBody()!=null)
{
Log.d("Message::",message.getBody());
}
}
});
}
};
return super.onStartCommand(intent, flags, startId);
}
}
Whenever is send a packet i am getting this following exception .I don't kno why its arising
Exception in packet listener java.lang.NullPointerException: Attempt to invoke interface method 'void org.jivesoftware.smack.chat.ChatManagerListener.chatCreated(org.jivesoftware.smack.chat.Chat, boolean)' on a null object reference
at org.jivesoftware.smack.chat.ChatManager.createChat(ChatManager.java:255)
at org.jivesoftware.smack.chat.ChatManager.createChat(ChatManager.java:287)
In simple terms i want to know how to implement ChatMessage listener in the service.Please be kind
You need to createchat once you successfully connected & authenticated
Once you got the instance of ChatManager.For package transmission you need to createchat with peer/group check this link for method to createchat.
chatManager = ChatManager.getInstanceFor(abstractXMPPConnection);
newChat = chatmanager.createChat(userid, chatManagerListener);
once you get the Chat instance you can send package & retrive on your chatmanagerListner
from newChat you can sendMessage
To get Package (message, chat)
You can try below code if your connection/authentication process is done successfully than
final Chat newChat = ChatManager.getInstanceFor(xmppConn).createChat(userJid, new MessageListener() {
#Override
public void processMessage(final Chat arg0, final Message arg1) {
LOG.info("Sent message: " + arg1.getBody());
}
});
try {
final Message message = new Message();
message.setFrom(chatProperties.getDomain());
message.setTo(userJid);
message.setType(Type.normal);
message.setBody(text);
message.setSubject("");
newChat.sendMessage(message);
xmppConn.disconnect();
} catch (final Exception e) {
LOG.error("Error while sending message to " + userName + ": ", e);
}
UPDATE
You can try using PacketListener.
XMPPConnection's addPacketListener method check this link for details.
Add PacketListener to XMPPConnection with PacketFilter type Message
But before adding packetlistner remove if already added any instance in xmppconnection.
Check below code
private PacketListener packetListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {
if (packet instanceof Message) {
Message message = (Message) packet;
String chatMessage = message.getBody();
}
}
};
private void regiSterPackateListner() {
PacketTypeFilter filter = new PacketTypeFilter(Message.class);
try {
if (packetListener != null) {
//Avoid adding multiple packetlistner
abstractXMPPConnection.removePacketListener(packetListener);
}
abstractXMPPConnection.addPacketListener(packetListener, filter);
} catch (Exception e) {
e.printStackTrace();
}
}
Refer to this example:
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
public class GoogleTalkDemo extends Thread{
private XMPPConnection xmppConnection;
public void connect(String server, int port, String s) throws Exception {
xmppConnection = new XMPPConnection(new ConnectionConfiguration(server, port,s));
xmppConnection.connect();
}
public void disconnect(){
if(xmppConnection != null){
xmppConnection.disconnect();
interrupt();
}
}
public void login(String username, String password) throws Exception{
connect("talk.google.com", 5222, "gmail.com");
xmppConnection.login(username, password);
}
public void run(){
try {
login("youtID#sample.com", "your password");
System.out.println("Login successful");
listeningForMessages();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception {
GoogleTalkDemo gtd = new GoogleTalkDemo();
gtd.run();
}
public void listeningForMessages() {
PacketFilter filter = new AndFilter(new PacketTypeFilter(Message.class));
PacketCollector collector = xmppConnection.createPacketCollector(filter);
while (true) {
Packet packet = collector.nextResult();
if (packet instanceof Message) {
Message message = (Message) packet;
if (message != null && message.getBody() != null)
System.out.println("Received message from "
+ packet.getFrom() + " : "
+ (message != null ? message.getBody() : "NULL"));
}
}
}
}
Hope it will help you.
A simple demo about sending and receiving masseges:
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
public class Test {
public static void main(String args[]) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1", 5222);
XMPPConnection connection = new XMPPConnection(config);
connection.connect();
connection.login("userx", "123456");
ChatManager cm = connection.getChatManager();
Chat chat = cm.createChat("tongqian#tsw-PC", null);
/*
* add listener
*/
cm.addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean create) {
chat.addMessageListener(new MessageListener() {
#Override
public void processMessage(Chat chat, Message msg) {
System.out.println(chat.getParticipant() + ":" + msg.getBody());
}
});
}
});
chat.sendMessage("hello");
while(true);
//connection.disconnect();
}
}
i'm newbie in nodejs and express.io , in android application i'm wrote this simple code to connect from android or java but iget connection error
app = require('express.io')()
app.http().io()
// Broadcast the new visitor event on ready route.
app.io.route('ready', function(req) {
req.io.broadcast('new visitor')
console.log('ready');
})
// Send client html.
app.get('/', function(req, res) {
//res.sendfile(__dirname + '/client.html')
req.io.broadcast('new visitor')
console.log('hello');
})
app.listen(7076)
this code maybe is correct, after opening http://192.168.1.5:7076 link in browser i get hello message, now with below code i'm try to connect but i get connection error:
private static final String SERVER_ADDRESS = "http://192.168.1.5:7076";
private Socket mSocket;
{
try {
mSocket = IO.socket(SERVER_ADDRESS);
} catch (URISyntaxException e) {
Log.e("Error URI", String.valueOf(e));
throw new RuntimeException(e);
}
}
public class ActivityHome extends FragmentActivity {
...
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on("new message", onNewMessage);
mSocket.on("user joined", onUserJoined);
mSocket.on("user left", onUserLeft);
mSocket.on("typing", onTyping);
mSocket.on("stop typing", onStopTyping);
mSocket.connect();
...
}
private Emitter.Listener onConnectError = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"CONNECT ERROR", Toast.LENGTH_LONG).show();
}
});
}
};
I'm new to Jerry, and trying to implement WebSocket Client on Jetty9.
I saw an example on Jetty8.
org.eclipse.jetty.websocket Class WebSocketClient
http://archive.eclipse.org/jetty/8.0.0.v20110901/apidocs/org/eclipse/jetty/websocket/WebSocketClient.html
to create a new instance of WebSocketClient is :
WebSocketClientFactory factory = new WebSocketClientFactory();
factory.start();
WebSocketClient client = factory.newWebSocketClient();
// Configure the client
WebSocket.Connection connection = client.open(new
URI("ws://127.0.0.1:8080/"), new WebSocket.OnTextMessage()
{
public void onOpen(Connection connection)
{
// open notification
}
public void onClose(int closeCode, String message)
{
// close notification
}
public void onMessage(String data)
{
// handle incoming message
}
}).get(5, TimeUnit.SECONDS);
connection.sendMessage("Hello World");
However, I've never seen a document for Jetty9 for this.
So far, referring to
org.eclipse.jetty.websocket.common
Interface SessionFactory
//----------------------------------------------
WebSocketSession createSession(URI requestURI,
EventDriver websocket,
LogicalConnection connection)
//----------------------------------------------
I've tried
private WebSocketSessionFactory factory = new WebSocketSessionFactory();
try
{
WebSocketSession session = factory.createSession(uri,
eventDriver, connection);
RemoteEndpoint ep = session.getRemote();
}
catch (Exception ex)
{
System.out.println("=ERROR= " + ex);
//=ERROR= java.lang.NullPointerException
}
private EventDriver eventDriver = new EventDriver()
{
#Override
public WebSocketPolicy getPolicy()
{
return null;
}
//......................................
#Override
public void incomingFrame(Frame frame)
{
}
};
private LogicalConnection connection = new LogicalConnection()
{
#Override
public void close()
{
}
//...............................
#Override
public void resume()
{
}
};
but I've encounter java.lang.NullPointerException
How do we implement Jetty9 WebSocket Client ??
Thanks for your advise.
Hope this helpful: EventClient.java