I would execute an example to use OpenFire and XMPP with Java language:
public class TestXMPP {
public static void main(String args[]) throws Exception {
ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1");
XMPPConnection xmppConnection = new XMPPConnection(config);
try {
xmppConnection.connect();
xmppConnection.login("serveur22", "serveur22");
Message msg = new Message("salon#conference.localhost/serveur22", Message.Type.normal); // Line 10
msg.setBody("Test Message TestXMPP.java");
xmppConnection.sendPacket(msg);
xmppConnection.disconnect();
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
I can send to a specific login but not for a room...
I think line 10 is not correct...
If you have a solution, thanks a lot
Assuming your XMPP domain is localhost, as you have coded it, try removing the resource from the JID.
Change this:
salon#conference.localhost/serveur22
to
salon#conference.localhost
Related
I'm trying to connect to the on-line broker https://test.mosquitto.org/ using the code below and the Paho library in Java:
private final String brokerURI = "test.mosquitto.org:1883"; //should be changed to 8883 with SSL
try { //tentativo di creazione del client
client = new MqttClient(brokerURI, idClient); <--NullPointerException here
client.setCallback(new ClientCallback(codaTopic, codaMessaggi, finestra)); //set delle callback
setConnectionOptions(); //set delle opzioni connessione
client.connect(opzioni); //connessione al server
} catch (MqttException e) {
System.err.println(e.getMessage());
System.err.println("Connessione fallita Client, riavviare il sistema.");
}
Connection options are set here:
private void setConnectionOptions() {
opzioni = new MqttConnectOptions();
opzioni.setAutomaticReconnect(true);
opzioni.setCleanSession(false);
opzioni.setConnectionTimeout(30);
opzioni.setKeepAliveInterval(60);
}
but it continues to show a NullPointerException while creating the MqttClient. In particular the console displays:
Exception in thread "Thread-3" java.lang.NullPointerException
at org.eclipse.paho.client.mqttv3.MqttConnectOptions.validateURI(MqttConnectOptions.java:489)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.<init>(MqttAsyncClient.java:291)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.<init>(MqttAsyncClient.java:185)
at org.eclipse.paho.client.mqttv3.MqttClient.<init>(MqttClient.java:226)
at org.eclipse.paho.client.mqttv3.MqttClient.<init>(MqttClient.java:138)
at client.Client.run(Client.java:78)
How can i manage to connect and use SSL?
Surfing the net none of the tutorial or guides were useful, I already downloaded the mosquitto.org.crtfile for SSL connection, but i don't know where to use it and I found no tutorials.
EDIT
Changing the BrokerUri to
private final String brokerURI = "tcp://test.mosquitto.org:1883"; //indirizzo broker
the console shows the error
Client non connesso (32104)
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:31)
at org.eclipse.paho.client.mqttv3.internal.ClientComms.sendNoWait(ClientComms.java:166)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.subscribe(MqttAsyncClient.java:835)
at org.eclipse.paho.client.mqttv3.MqttClient.subscribe(MqttClient.java:322)
at org.eclipse.paho.client.mqttv3.MqttClient.subscribe(MqttClient.java:315)
at client.Client.subscribe(Client.java:214)
at client.Client.run(Client.java:89)
while trying to subscribe to a Topic with the instruction
client.subscribe(topic, 1);
The topic argument is a String that contains the topic name.
Mosquitto's URI needs the protocol. Taking a look at its source code, this is where your exception is being thrown, class MqttConnectOpts.java :
protected static int validateURI(String srvURI) {
try {
URI vURI = new URI(srvURI);
if (!vURI.getPath().equals("")) {
throw new IllegalArgumentException(srvURI);
}
if (vURI.getScheme().equals("tcp")) {
return URI_TYPE_TCP;
}
else if (vURI.getScheme().equals("ssl")) {
return URI_TYPE_SSL;
}
else if (vURI.getScheme().equals("local")) {
return URI_TYPE_LOCAL;
}
else {
throw new IllegalArgumentException(srvURI);
}
} catch (URISyntaxException ex) {
throw new IllegalArgumentException(srvURI);
}
}
So, it accepts 3 types of protocol prefixes: tcp, ssl, local. Regarding your example, you could try it this way:
TCP
private final String brokerURI = "tcp://test.mosquitto.org:1883";
SSL
private final String brokerURI = "ssl://test.mosquitto.org:8883";
I am trying to create a socket connection between a .Net server application and Java Client Application.
I am getting an error from the java client application:
Connection refused: connect
Notes:
Communicating with a .Net Client Application, works fine.
I have disables the windows firewall
Undoubtedly, I am running the server application in the background and then I am running the client application
Following are my server code (C#):
public class Server
{
public Server()
{
CreateListener();
}
public void CreateListener()
{
// Create an instance of the TcpListener class.
TcpListener tcpListener = null;
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
string output;
try
{
// Set the listener on the local IP address
// and specify the port.
tcpListener = new TcpListener(ipAddress, 13);
tcpListener.Start();
output = "Waiting for a connection...";
}
catch (Exception e)
{
output = "Error: " + e.ToString();
MessageBox.Show(output);
}
}
}
and client application code (Java):
public class smtpClient {
public void Send() {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try {
smtpSocket = new Socket("localhost", 13); // FAILURE
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
It fails at the following line in the Java Client Application:
smtpSocket = new Socket("localhost", 13);
I can't tell what is the issue you are facing, but you need to start with a solid foundation to discover these issues.
As a rule of thumb, you should always write one piece (typically the server) first and verify connectivity (say using telnet) and then write the other piece (typically client) and verify its connectivity.
I always keep a Standard Client and Server handy to test whether its my code or its the environment/configuration.
Below is a sample code that works fine to test connectivity.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class ClientServer {
static void Main() {
new Thread(() => { StartServer("localhost", 5013); }).Start();
Thread.Sleep(100);
Console.WriteLine("\nPress enter to start the client...");
Console.ReadLine();
StartClient("localhost", 5013);
}
public static void StartServer(string serverInterface, int port) {
try {
IPHostEntry hostInfo = Dns.GetHostEntry(serverInterface);
string hostName = hostInfo.HostName;
IPAddress ipAddress = hostInfo.AddressList[0];
var server = new TcpListener(ipAddress, port);
server.Start();
Console.WriteLine($"Waiting for a connection at {server.LocalEndpoint}");
Console.WriteLine("Press ctrl+c to exit server...");
while (true) {
TcpClient client = server.AcceptTcpClient();
Console.WriteLine($"Server says - Client connected: {client.Client.RemoteEndPoint}");
ThreadPool.QueueUserWorkItem((state) => {
using (var _client = (TcpClient)state)
using (NetworkStream stream = _client.GetStream()) {
string msg = stream.ReadAsciiData();
if (msg == "Hello!") {
stream.WriteAsciiData($"Time:{DateTime.Now: yyyy/MM/dd HH:mm zzz}. Server name is {hostName}");
}
}
}, client);
}
} catch (Exception e) {
Console.WriteLine(e);
}
}
public static void StartClient(string serverInterface, int port) {
Console.WriteLine("Client started...");
try {
using (var client = new TcpClient(serverInterface, port))
using (NetworkStream stream = client.GetStream()) {
Console.WriteLine("Client says - Hello!");
stream.Write(Encoding.ASCII.GetBytes("Hello!"));
string msg = stream.ReadAsciiData();
Console.WriteLine($"Client says - Message from server: Server#{client.Client.RemoteEndPoint}: {msg}");
}
} catch (Exception e) {
Console.WriteLine(e);
}
Console.WriteLine("Client exited");
}
}
static class Utils {
public static void WriteAsciiData(this NetworkStream stream, string data) {
stream.Write(Encoding.ASCII.GetBytes(data));
}
public static string ReadAsciiData(this NetworkStream stream) {
var buffer = new byte[1024];
int read = stream.Read(buffer, 0, buffer.Length);
return Encoding.ASCII.GetString(buffer, 0, read);
}
public static void Write(this NetworkStream stream, byte[] data) {
stream.Write(data, 0, data.Length);
}
}
Now to your specific problem,
The choice of port 13, is not ideal for testing. Usually all ports below 1024 are considered privileged. i.e. a firewall or antivirus might block your attempt to listen on that port
Remember that IPV6 addresses plays a role. Your machine might have that enabled or disabled based on your configuration. You want to make sure that if your server is listening on a IPv6 interface, then your client also connects on the same
Which brings us to another related point: Irrespective of you are using IPv6 interface or not, the client needs to connect to the same interface the server is listening on. This might seem obvious, but is often missed. A typical machine
has at-least 2 interfaces: One for localhost (127...* called loopback interface) and another non local (typically 10...* or 192...*, but not restricted to it). It can so happen (especially when you pick the first available interface to bind your server without knowing which one it is) that server might be listening on non loopback interface like say 192.168.1.10 interface and the client might be connecting to 127.0.0.1, and you can see why the client will get "connection refused" errors
The sample code above works and you can test your code with it. You can us telnet for a client or just my sample code. You can play around changing the serverInterface values to some surprising discoveries which are accentuated by
ipAddress = hostInfo.AddressList[0] line
Hope this helps you with your debugging
I'm following this tutorial to establish a WebSocket connection to a server:
http://www.eclipse.org/jetty/documentation/current/jetty-websocket-client-api.html
The code (same as the tutorial):
import java.net.URI;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
/**
* Example of a simple Echo Client.
*/
public class SimpleEchoClient {
public static void main(String[] args) {
String destUri = "ws://echo.websocket.org";
if (args.length > 0) {
destUri = args[0];
}
WebSocketClient client = new WebSocketClient();
SimpleEchoClient socket = new SimpleEchoClient();
try {
client.start();
URI echoUri = new URI(destUri);
ClientUpgradeRequest request = new ClientUpgradeRequest();
client.connect(socket, echoUri, request);
System.out.printf("Connecting to : %s%n", echoUri);
// socket.awaitClose(5, TimeUnit.SECONDS);
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
client.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Errors:
2014-08-07 21:49:00.346:INFO::main: Logging initialized #86ms
org.eclipse.jetty.websocket.api.InvalidWebSocketException:
SimpleEchoClient is not a valid WebSocket object.
Object must obey one of the following rules:
(1) class implements org.eclipse.jetty.websocket.api.WebSocketListener or
(2) class is annotated with #org.eclipse.jetty.websocket.api.annotations.WebSocket
at org.eclipse.jetty.websocket.common.events.EventDriverFactory.wrap(EventDriverFactory.java:145)
at org.eclipse.jetty.websocket.client.WebSocketClient.connect(WebSocketClient.java:200)
at org.eclipse.jetty.websocket.client.WebSocketClient.connect(WebSocketClient.java:144)
at SimpleEchoClient.main(SimpleEchoClient.java:31)
I'm not too sure what is wrong with my imported jar file. Maybe it is the wrong one? I'm using this: http://mvnrepository.com/artifact/org.eclipse.jetty.websocket/websocket-client/9.2.2.v20140723
Surely there must be an easier way to establish a connection via Jetty Websocket and start receiving data?
As Kayman explained in the comment, your problem with the socket handler implementation, use the latest release here explained with an example(same you used but correct) http://www.eclipse.org/jetty/documentation/current/jetty-websocket-client-api.html
It looks like the documentation is out-of-date with the current version you are using. Try rolling back to a more stable version of 9.2.x like:
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-client</artifactId>
<version>9.2.0.RC0</version>
</dependency>
I am trying to teach myself some networking in Java using the Kryonet library. The following code is almost identical to the code in the kyronet tutorial. https://code.google.com/p/kryonet/#Running_a_server
The client is successfully sending the message "Here is the request!" to the server (the server is printing it out) however the client is not receiving any response from the server even though the server is sending one.
I've tried unsuccessfully to fix it, can anyone see or suggest a possible problem/solution with the code?
(The code follows)
Client
public class Client_test {
Client client = new Client();
public Client_test() {
Kryo kryo = client.getKryo();
kryo.register(SomeRequest.class);
kryo.register(SomeResponse.class);
client.start();
try {
client.connect(50000, "127.0.0.1", 54555, 54777);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client.addListener(new Listener() {
public void received (Connection connection, Object object) {
if (object instanceof SomeResponse) {
SomeResponse response = (SomeResponse)object;
System.out.println(response.text);
}
}
});
SomeRequest request = new SomeRequest();
request.text = "Here is the request!";
client.sendTCP(request);
}
}
Server
public class ServerGame {
Server server = new Server();
public ServerGame() {
Kryo kryo = server.getKryo();
kryo.register(SomeRequest.class);
kryo.register(SomeResponse.class);
server.start();
try {
server.bind(54555, 54777);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
server.addListener(new Listener() {
public void received (Connection connection, Object object) {
if (object instanceof SomeRequest) {
SomeRequest request = (SomeRequest)object;
System.out.println(request.text);
SomeResponse response = new SomeResponse();
response.text = "Thanks!";
connection.sendTCP(response);
}
}
});
}
}
Response & Request classes
public class SomeRequest {
public String text;
public SomeRequest(){}
}
public class SomeResponse {
public String text;
public SomeResponse(){}
}
After many hours watching youtube videos and sifting through the web I found the answer. Which I will post on here as it seems that quite a few people have had this problem so I would like to spread the word.
Basically the client would shut down immediately, before it could receive and output the message packet. This is because "Starting with r122, client update threads were made into daemon threads, causing the child processes to close as soon as they finish initializing.", the solution is "Maybe you could use this? new Thread(client).start();".
So basically instead of using
client.start();
to start the client thread you must use
new Thread(client).start();
Which I believe stops the thread being made into a daemon thread which therefore stops the problem.
Source: https://groups.google.com/forum/?fromgroups#!topic/kryonet-users/QTHiVmqljgE
Yes, inject a tool like Fiddler in between the two so you can see the traffic going back and forth. It's always easier to debug with greater transparency, more information.
how to run java tcp server in window azure?
can window azure do it?
I find so many article about java application for window azure,they is that open a JSP web project in eclipse, and than use worker role publish it in window azure, but my tcp server is general java project, so how to publish it to window azure?
my tcp server:
public class test {
private static int serverport = 12345;
private static ServerSocket serverSocket;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(serverport);
System.out.println("Server is start.");
while (!serverSocket.isClosed()) {
System.out.println("Wait new clinet connect!");
waitNewPlayer();
}
} catch (IOException e) {
System.out.println("Server Socket ERROR");
}
}
public static void waitNewPlayer() {
try {
Socket socket = serverSocket.accept();
System.out.println(socket.getInetAddress().getHostAddress()+"'s socket is connected now!");
createNewUser(socket);
} catch (IOException e) {
}
}
public static void createNewUser(final Socket socket) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println("nangnang");
} catch (IOException e) {
System.out.println("Socket is closed!");
}
System.out.println("This socket is removed form the player array!");
}
});
t.start();
}
}
You should be able to run an app like this in Azure, but you'll need to take care of a couple of things:
Open an Input Endpoint for your worker role - this opens the port to the outside world. You then need to either map it to the exact same port internally, or let Azure pick a port for you (and then you can ask the role environment which port you've been assigned, and open that port in your code instead of 12345)
For all your println's, you'd need to remote-desktop to see them, or you need to push them to diagnostics logging so you can see those debug statements via an external tool like Cerebrata's Diagnostics Manager.
As far as publishing: It's the same as the jsp examples you've seen: you build an Azure project to go along with your Java project, you set up the role size and instance count, create input endpoints, optionally create a cache, set up configuration settings for storage accounts, create a package to run in emulator or in the cloud, etc.
You might also want to try AzureRunMe which also supports Azure Java Project. http://azurerunme.codeplex.com/