I'm using Postman to test Chat feature (socket.io technology with version 2).
Currently, i have to implement Chat test cases using Java.
Postman request information:
1. Socket server: https://hc-socketio-example.xyz
2. Header.authorization: xxx
3. Header.source: app
4. Message.text with JSON format:
{ "ticketId": "63bcc910c22293b4b0495fe4", "content": "test ", "type": "text"}
My Java code to connect socket server:
URI uri = URI.create("https://hc-socket.unibag.xyz");
// #formatter:off
IO.Options options = IO.Options.builder().build();
// #formatter:on
Socket socket = IO.socket(uri, options);
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
System.out.println("Connected to server...");
}
});
socket.connect();
My issues need the help:
Look like my code gets wrong because no String "Connected to server..." printed.
I don't know the way to set the header or request: "authentication", "source"
I'm not sure the way to send JSON message like above:
COULD SOMEONE TAKE A LOOK AND GIVE ME THE ADVISE IN ORDER I COULD FIX MY CODE?
THANKS A LOT IN ADVANCE.
I tried researching on the internet some examples but no luck. I'm confusing about the way to send socket request.
Chats are typically facilitated through web sockets over http, assuming you want to build a chat system that runs over the internet.
I have a working program written that can establish a connection and send/receive messages from the Chat Server.
As a prerequisite you need a third party library.
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.0</version>
</dependency>
Also accompanied is the piece of client code that can send headers, get acknowledgement for connections and send/receive json messages
public class ChatWebSocketClient extends WebSocketClient{
public ChatWebSocketClient(URI serverURI, Map<String, String> headers) {
super(serverURI, new Draft_17(), headers, 0);
}
#Override
public void onOpen(ServerHandshake handshakedata) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(String message) {
// TODO Auto-generated method stub
}
#Override
public void onClose(int code, String reason, boolean remote) {
// TODO Auto-generated method stub
}
#Override
public void onError(Exception ex) {
// TODO Auto-generated method stub
}
public static void main(String args[]) throws Exception {
Map<String, String> headers = new HashMap();
headers.put("header1", "value1 for header1");
ChatWebSocketClient client = new ChatWebSocketClient(new URI("Remote_Chat_EndPoint"), headers);
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
#Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return new java.security.cert.X509Certificate[]{};
}
#Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
}};
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
client.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sc));
client.connect();
client.send("{\"key\":\"Hello World\"}");
}
}
Related
I have a new thread that creates a MqttAsyncClient instance and connects to a remote server. After connecting the client subscribes to a specific topic. If I use the MqttClient instead of the MqttAsyncClient I receive the messages, but if I use the MqttAsyncClient no messages are received. Below is my code, would someone please take a moment to see if I have something missing or incorrect?
public class MqttEventReceiver implements Runnable {
private static final String CLIENT_ID = UUID.randomUUID().toString();
private IMqttAsyncClient client = null;
public MqttEventReceiver(String apiStreamingUri, String
connectionAccessToken) {
}
private MqttCallback mqttCallback = new MqttCallback() {
public void messageArrived(String topic, MqttMessage message) throws Exception {
String incomingMsg = new String(message.getPayload());
LOG.info("Message: ", new String(payload));
}
public void deliveryComplete(IMqttDeliveryToken arg0) {
// TODO Auto-generated method stub
}
public void connectionLost(Throwable arg0) {
// TODO Auto-generated method stub
}
};
#Override
public void run() {
String tmpDir = System.getProperty("java.io.tmpdir");
MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
//make the connect request. this request establishes a permanent connection
MqttConnectOptions options = new MqttConnectOptions();
options.setAutomaticReconnect(true);
options.setCleanSession(true);
options.setConnectionTimeout(10);
options.setUserName("authorization");
options.setPassword(connectionAccessToken.toCharArray());
Long threadId = successfullyConnected();
client = new MqttAsyncClient(apiStreamingUri, CLIENT_ID, dataStore);
client.setCallback(mqttCallback);
client.connect(options).waitForCompletion();
client.subscribe("topic", 1).waitForCompletion();
}
}
Turns out it was the QoS setting causing the message to be delivered slowly. I set the QoS to 0 and the message was delivered promptly.
I'm working in a project in Java and I need to follow some twitter account to collect data about the traffic.
I started using the Twitter API but suddenly i found the limit too low so I changed to the stream API. Here there is no limit but I only know how to search something into the currect stream, not to get only the streams from the accounts I want.
Is that posiible with the twitter4J api?
My code is the following one:
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
StatusListener listener = new StatusListener() {
#Override
public void onException(Exception arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDeletionNotice(StatusDeletionNotice arg0) {
// TODO Auto-generated method stub
}
#Override
public void onScrubGeo(long arg0, long arg1) {
// TODO Auto-generated method stub
}
#Override
public void onStatus(Status status) {
//I process the tweet.
}
#Override
public void onTrackLimitationNotice(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStallWarning(StallWarning arg0) {
// TODO Auto-generated method stub
}
};
FilterQuery fq = new FilterQuery();
String keywords[] = {"a","e","i","o","u"};
fq.track(keywords);
twitterStream.addListener(listener);
twitterStream.filter(fq);
You can specify users you want to follow using the FilterQuery object, e.g.:
long[] userIds = { ...omitted... };
fq.follow(userIds);
twitterStream.filter(fq);
Be aware that when filtering Tweets only need to match one of the conditions, i.e. the track or follow, so you may need to do some manual filtering if you intend to use both.
For more information check out Twitter's documentation for the follow parameter and filter stream.
twitter.createFriendship("screenName");
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
My Kryonet server disconnects after 5000ms when I'm using this line for a connection
client.connect(5000, host, Network.port);
I thought the 5000 was the connection timeout but when I run the connection, it is able to connect and it receives the classes I send but it disconnects from the server after 5000ms.
I'm modifying the basic ChatClient.java provided with Kryonet.. Here's what I came up with.
import java.awt.EventQueue;
import java.io.IOException;
import com.badlogic.gdx.ApplicationListener;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.me.mygdxgame.Network.Obstacles;
public class GameClient implements ApplicationListener{
Client client;
String name;
public GameClient () {
client = new Client();
client.start();
// For consistency, the classes to be sent over the network are
// registered by the same method for both the client and server.
Network.register(client);
client.addListener(new Listener() {
public void connected (Connection connection) {
System.out.println("connected");
}
public void received (Connection connection, Object object) {
if (object instanceof Obstacles) {
Obstacles obs = (Obstacles)object;
System.out.println("Obstacle recieved on client - " + obs.obstacles.size());
return;
}else {
System.out.println("invalid packet");
}
}
public void disconnected (Connection connection) {
EventQueue.invokeLater(new Runnable() {
public void run () {
client.close();
// Closing the frame calls the close listener which will stop the client's update thread.
}
});
}
});
final String host = "localhost";
// We'll do the connect on a new thread so the ChatFrame can show a progress bar.
// Connecting to localhost is usually so fast you won't see the progress bar.
new Thread("Connect") {
public void run () {
try {
client.connect(5000, host, Network.port);
// Server communication after connection can go here, or in Listener#connected().
} catch (IOException ex) {
ex.printStackTrace();
System.exit(1);
}
}
}.start();
}
#Override
public void create() {
// TODO Auto-generated method stub
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void render() {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
}
try to use client.SetKeepAliveTCP(int smallerthendisconnecttime);
The problem you are describing can arise if you configure your server for TCP and UDP but then have your client only connect via TCP.
If you're wanting to take advantage of the host discovery but only need a TCP connection thereafter then it is advisable that you "run a separate server for UDP discovery".
Basically, you need to be sure that client and server protocol usage matches (either both server and client are setup for only TCP, or both server and client are setup for both TCP and UDP).
I have some trouble getting application-to-application communication via web sockets (that is without a browser to work). Since this does not seem to be the most usual application of web sockets, I wonder if anybody has any experience doing this.
Why do I want to use web sockets?
Because of firewall issues I need to go through port 80/8080 (and I need to continue to handle some other HTTP communication, so I can't just use plain TCP/IP socket communication).
How did I try to make this work?
I'm using Jetty 8.0 both for the server and for the client. My server code:
public class WebSocketTestServlet extends WebSocketServlet {
public WebSocket doWebSocketConnect(HttpServletRequest arg0, String arg1) {
return new TestWebSocket();
}
class TestWebSocket implements WebSocket, WebSocket.OnTextMessage
{
public void onClose(int arg0, String arg1) {
}
public void onOpen(Connection arg0) {
}
public void onMessage(String messageText) {
}
}
}
My client code:
public class MyWebSocketClient{
MyWebSocketClient() throws IOException
{
WebSocketClientFactory factory = new WebSocketClientFactory();
try {
factory.start();
} catch (Exception e1) {
e1.printStackTrace();
}
WebSocketClient client = factory.newWebSocketClient();
WebSocket.Connection connection = client.open(new URI("ws://myserver:8080/testws"), new WebSocket.OnTextMessage()
{
public void onOpen(Connection connection)
{
}
public void onClose(int closeCode, String message)
{
}
public void onMessage(String data)
{
}
}).get(50, TimeUnit.SECONDS)
}
What problem do I see?
A ProtocolException
Caused by: java.net.ProtocolException: Bad response status 302 Found
at org.eclipse.jetty.websocket.WebSocketClientFactory$HandshakeConnection.closed(WebSocketClientFactory.java:423)
at org.eclipse.jetty.websocket.WebSocketClientFactory$WebSocketClientSelector.endPointClosed(WebSocketClientFactory.java:235)
at org.eclipse.jetty.io.nio.SelectorManager$SelectSet.destroyEndPoint(SelectorManager.java:948)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.doUpdateKey(SelectChannelEndPoint.java:523)
at org.eclipse.jetty.io.nio.SelectorManager$SelectSet.doSelect(SelectorManager.java:469)
at org.eclipse.jetty.io.nio.SelectorManager$1.run(SelectorManager.java:283)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:598)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:533)
at java.lang.Thread.run(Thread.java:619)
Any idea why this is not working?
Try to add "/" at the end of your address in the client's code:
"ws://myserver:8080/testws/"
It just fixed the issue for me.
Trying to do something similar to allow WS calls to an embedded Jetty REST API...here's my echo test code (Jetty 7), HTH
public class myApiSocketServlet extends WebSocketServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException ,IOException
{
OutputStream responseBody = response.getOutputStream();
responseBody.write("Socket API".getBytes());
responseBody.close();
}
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol)
{
return new APIWebSocket();
}
class APIWebSocket implements WebSocket, WebSocket.OnTextMessage
{
Connection connection;
#Override
public void onClose(int arg0, String arg1)
{
}
#Override
public void onOpen(Connection c)
{
connection = c;
}
#Override
public void onMessage(String msg)
{
try
{
this.connection.sendMessage("I received: " + msg);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}