How to solve webSockets protocol violation in android autobahn - android

In my android application I want to use the autobahn library to use websockets.
I have done server side code using spring.
Simple socket is working when i am try pub sub then i get error.
My Code :-
final String wsuri = "ws://localhost:8080/ws";
try {
mConnection.connect(wsuri, new Wamp.ConnectionHandler()
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri);
mConnection.subscribe("ws://localhost8080/ws/onetoone",
MyEvent1.class, new Wamp.EventHandler() {
#Override
public void onEvent(String topicUri, Object event) {
Log.d(TAG, "Status: Connected to " + event);
}
});
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection lost." + " " + reason);
}
});
} catch (Exception e) {
Log.d(TAG, e.toString());
}
OutOut :-
de.tavendo.autobahn.WebSocketConnection: created
de.tavendo.autobahn.WebSocketReader: created
de.tavendo.autobahn.WampReader: created
de.tavendo.autobahn.WampConnection: reader created and started
de.tavendo.autobahn.WebSocketWriter: created
de.tavendo.autobahn.WampWriter: created
de.tavendo.autobahn.WampConnection: writer created and started
de.tavendo.autobahn.WebSocketReader: running
de.tavendo.autobahn.WebSocketReader: run() : WebSocketException
(de.tavendo.autobahn.WebSocketException: RSV != 0 and no extension negotiated)
de.tavendo.autobahn.WebSocketReader: ended
de.tavendo.autobahn.WebSocketConnection: opening handshake received
Status: Connected to ws://localhost:8080/Spring4WebSocket/add
de.tavendo.autobahn.WebSocketConnection: fail connection [code = 4, reason = WebSockets protocol violation
de.tavendo.autobahn.WebSocketReader: quit
de.tavendo.autobahn.WebSocketConnection: waiting for reader to finish
de.tavendo.autobahn.WebSocketConnection: readr thread done
de.tavendo.autobahn.WebSocketConnection: sending close message over socket
de.tavendo.autobahn.WebSocketWriter: ended
de.tavendo.autobahn.WebSocketConnection: waiting for writer to finish
de.tavendo.autobahn.WebSocketConnection: writer thread done
Connection lost. WebSockets protocol violation
I have pass ip address place on local host(my PC ip address).
Any have solution for how to solve web Sockets protocol violation in android autobahn.
Please help for above problem.

The error message:
RSV != 0 and no extension negotiated
implies that one or more of the reserved bits of a WebSocket frame which your WebSocket client received from your WebSocket server was not 0. If no WebSocket extension was negotiated (during the WebSocket opening handshake) as the error message claims, the reserved bits should be all zeros.
Check whether the endpoint of your WebSocket server is properly speaking the WebSocket protocol.

Related

UDP socket programming is not working for Android 6.0(API 23) [duplicate]

I am trying to write a simple android chat app. I have created a service class which handles all the networking communication. The DatagramSocket binding is in a separate thread. Once in while I am getting this error and the app crashes:
java.net.BindException: bind failed: EADDRINUSE (Address already in use)
at libcore.io.IoBridge.bind(IoBridge.java:89)
at java.net.PlainDatagramSocketImpl.bind(PlainDatagramSocketImpl.java:68)
at java.net.DatagramSocket.createSocket(DatagramSocket.java:133)
at java.net.DatagramSocket.<init>(DatagramSocket.java:78)
and this is the code which prodruces it. The error occur on the line with new DatagramSocket How can I avoid this error? Thank you.
private class ComThread extends Thread {
private static final int BCAST_PORT = 8779;
DatagramSocket mSocket;
InetAddress myBcastIP, myLocalIP;
public ComThread() {
try {
myBcastIP = getBroadcastAddress();
if (D)
Log.d(TAG, "my bcast ip : " + myBcastIP);
myLocalIP = getLocalAddress();
if (D)
Log.d(TAG, "my local ip : " + myLocalIP);
if (mSocket == null) {
mSocket = new DatagramSocket(BCAST_PORT);
mSocket.setReuseAddress(true);
mSocket.setBroadcast(true);
}
} catch (IOException e) {
Log.e(TAG, "Could not make socket", e);
}
}
Since Sean asked for the code, I have translated Nikola's answer to the following code, which is similar to what I am using in my app, in case it is useful:
if (mSocket == null) {
mSocket = new DatagramSocket(null);
mSocket.setReuseAddress(true);
mSocket.setBroadcast(true);
mSocket.bind(new InetSocketAddress(BCAST_PORT));
}
You need to set SO_REUSEADDR before binding. Don't specify port in the constructor - create unbound socket instead with DatagramSocket(null), then set options, then bind() explicitly.
Another reason that I faced,
In case you access a method that using your socket from an external thread, you have to make sure that the thread won't access the method more than once in the same time(or in another words won't create the socket more than one time), and despite the send and receive methods of the DatagramSocket are threadsafe, the construction of the DatagramSocket object is not, so you have to just synchronize the method that is capable of creating the DatagramSocket socket:
synchronized public void my_datagram_socket() throws Exception{
// create the socket
// operations through the socket
// whatever you want
}

Is the usage of TcpClients in unity3d for android possible?

I am trying to make an andorid app that commuicates with my server via Unity 5.4. The Devices need to be in the same network to do so.
For that i am using System.Net.Sockets and a TcpClient to connect to my server. Everything works well when i run it out of the Editor, or build it as a Windows standalone.The communication between a pc hosting the service and a diffrent pc running the standalone is possible and working as intended. As soon as i build it as an .apk and install it on my smartphone i will get a SocketException. Also my phone is stuck loading for quite some time
Is using a TcpClient, is that possible on android with unity3d ?
The Exception i get is:
System.Net.Sockets.SocketException: Connection timed out
I made sure that both devices are in the same network, e.g. the Ip for my Pc hosting the server is 192.168.178.24 and the ip for my smartphone is 192.168.178.113.
The ports required are open and the firewall lets data through.
I am runnig this code in Unity:
private TcpClient client;
private StreamWriter writer;
void Start()
{
try
{
client = new TcpClient(AddressFamily.InterNetwork);
IPAddress ipAddress = IPAddress.Parse(PlayerPrefs.GetString(MenuManager.IpPlayerPrefKey));
Debug.Log(ipAddress.ToString());
client.Connect(ipAddress, 11000);
writer = new StreamWriter(client.GetStream());
Debug.Log("connected");
}
catch (ArgumentNullException ane)
{
Debug.Log(string.Format("ArgumentNullException : {0}", ane.ToString()));
}
catch (SocketException se)
{
Debug.Log(string.Format("SocketException : {0}", se.ToString()));
}
catch (Exception e)
{
Debug.Log(string.Format("Unexpected exception : {0}", e.ToString()));
}
}
i double checked if the Ip adress recieved from the player prefs is correct, it is.
Has someone an idea what causes it to not even establish a connection ? I tried Wireshark on my pc, it didn't show any incoming packages, so my guess is the mistake is sometimes during establishing the connection.
Here is an image for my Log output from the smartphone:
LogCat Output
Edit: Server Code
public class ServiceListener
{
public TcpListener Listener;
public void StartListening()
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = Array.Find<IPAddress>(ipHostInfo.AddressList, ipMatch => ipMatch.AddressFamily == AddressFamily.InterNetwork);
Listener = new TcpListener(ipAddress, 11000);
Listener.Start();
}
public void StopListening()
{
Listener.Stop();
}
}
static void Main()
{
ServiceListener currentListener = new ServiceListener();
currentListener.StartListening();
TcpClient currentClient = currentListener.Listener.AcceptTcpClient();
StreamReader reader = new StreamReader(currentClient.GetStream());
Console.WriteLine("Connected");
while (true)
{
byte[] messageBytes = new byte[1024];
if (!reader.EndOfStream)
{
string message = reader.ReadLine();
string[] messageParts = message.Split('|');
int xOffset = int.Parse(messageParts[0]);
int yOffset = int.Parse(messageParts[1]);
bool leftClick = bool.Parse(messageParts[2]);
bool rightClick = bool.Parse(messageParts[3]);
Console.WriteLine(string.Format("x:{0},y:{1},left:{2},right:{3}", xOffset, yOffset, leftClick, rightClick));
}
else
{
currentClient = currentListener.Listener.AcceptTcpClient();
reader = new StreamReader(currentClient.GetStream());
}
}
}
Is using a TcpClient, is that possible on android with unity3d ?
Yes, it is. It is very possible and should work.
Your problem is very likely to come from this line of code:
IPAddress ipAddress = IPAddress.Parse(PlayerPrefs.GetString(MenuManager.IpPlayerPrefKey));
Since your hosting server IP is 192.168.178.24. Hardcode the value for testing purposes to see if PlayerPrefs.GetString(MenuManager.IpPlayerPrefKey) is returning an invalid IP Address.
Maybe something like:
IPAddress ipAddress = IPAddress.Parse("192.168.178.24");
Another thing to do in your server code is to put Application.runInBackground = true; in your Start() function. This will make sure that your server is running even when the Applciation is not on focus.
Finally, you are currently using synchronous server socket. When connecting, receiving data from the server, Unity will block/freeze until that operation completes. You should use asynchronous socket or run your server and client code in another Thread. This does not look like the current problem but you will run into it later on.

Android client socket doesn't send data after some time

I'm developing an Android real-time-data app that sends data (floats and ints) to a server on the local subnet via a TCP socket. The problem I'm facing is that after sending some data simultaneously the socket doesn't send anymore data at all. I debugged the app and it shows that data is being sent but doesn't show up on the server. After this happens if I close the connection the server doesn't even get the notification that the connection has been terminated which it should according to my design model. Meanwhile I get an exception on the app saying it can not write to a broken pipe. This tells me that the problem is with the app because I also did test using a desktop app and I can send huge amounts of data to the server and it gets delivered.
And please keep in mind that the data size I'm talking about here is 252 bytes per packet.
Here's my class I'm using. (This runs in an AsyncTask object )
public class Network
{
private Socket handle;
public static enum TASK
{
TASK_CONNECT, TASK_SEND, TASK_CLOSE
}
public Network()
{
}
public String lastError = "";
public boolean Connect(String host, int port)
{
try
{
lastError = "Connecting to server.";
handle = new Socket(host, port);
handle.setTcpNoDelay(true); //
handle.setSendBufferSize(SIZE_OF_PACKET); ///==> These don't seem to help at all
handle.setKeepAlive(true); ///
return true;
}catch(IOException e)
{
lastError += e.getMessage() != null ? " "+ e.getMessage() : "";
return false;
}
}
private void err(String e){
System.err.println(e);
}
private boolean SendPacket(byte buffer[])
{
OutputStream oStream = null;
err("sending: " + buffer.length + " bytes");
try
{
lastError = "Obtaining output stream.";
oStream = handle.getOutputStream();
lastError = "Error sending data.";
oStream.write(buffer);
oStream.flush();
return true;
}catch(Exception e)
{
lastError += e.getMessage() != null ? " "+ e.getMessage() : "";
}
return false;
}
public void Close()
{
try{ handle.close(); handle = null; }catch(Exception e){} // swallow exception
}
}
I send my data in a loop depending on how many numbers I have. I tried a Google search but didn't find anything relevant. Has anyone experienced this before? It's making me mad now.
EDIT: Wireshark shows incoming "red" packets that don't reach the desktop app (server)
Look at this picture.
You can see the first few have Len > 0 the red ones have 0.
I think it's time Google interfaced the USB so we can use it. At least that'd would have been my first option.
Should you not be calling oStream.close() after you flush the stream, given that you never use it again?
Also, you say that this is being run in an AsyncTask object. Is it possible that multiple threads could be attempting to send packets at the same time? If so, you might need some form of synchronisation around the SendPacket method.
Ok. I solved the issue by using UDP instead. Thank you all.
But I still didn't find the source of the problem.

Xmpp connection using asmack and bonjour on android

I'm trying to do a server-less app for IM. I use apple bonjour protocol to discover xmpp services. But once I get those I can't connect to my host (linux computer using pidgin + bonjour).
Here is my code (taken from here) :
public class Xmpp extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... arg0)
{
ConnectionConfiguration connConfig =
new ConnectionConfiguration("192.168.0.11", 5298, "bonjour");
XMPPConnection connection = new XMPPConnection(connConfig);
try
{
// Connect to the server
connection.connect();
// Most servers require you to login before performing other tasks.
connection.login("grea08", "mypass");
// Start a new conversation with John Doe and send him a message.
Chat chat = connection.getChatManager().createChat("grea09#192.168.0.11", new MessageListener() {
public void processMessage(Chat chat, Message message) {
// Print out any messages we get back to standard out.
Log.v(getClass().getName(), "Received message: " + message);
}
});
chat.sendMessage("Howdy!");
} catch (XMPPException e)
{
// TODO Auto-generated catch block
Log.e(getClass().getName(), "Xmpp error !", e);
}
// Disconnect from the server
connection.disconnect();
return null;
}
}
I've got an XmppException "No response from server". I think that the host is not an XMPP server and we must use the protocol this way.
Smack and aSmack has no support for XEP-0174 (aka. link-local or serverless messaging). Jonas patches never made it into the trunk. The corresponding issue to track is SMACK-262.
Gibberbot open source project supports XMPP and Bonjour serverless communication.
It also can be installed from Google Play.
Perhaps you can check out its sources and extract the relevant code for your app. :-)
Try creating your XMPPConnection with a configuration:
ConnectionConfiguration config = new ConnectionConfiguration("192.189.0.11", port);
//Set optional configurations on the config object.
Connection connection = new XMPPConnection(config);

Android, Client-Server app, Bad Socket Exception

I have a simple client-server app on android. the android service communicates with the server via tcp sockets. the service sends a simple String to server which works. the server processes the string and sends back an object to the android service. the object implements the serializable interface. the object "leaves" the server successfully but at the point where the android service receives the object (socket.readObject()) I get to following exception:
java.net.SocketException: Bad socket
I've never seen this. What does that mean?
Edit:
Method where exception gets thrown:
private static void startContextListener(){
new Thread(){
public void run(){
try{
while(contextsocket != null && !contextsocket.isClosed() && inContext.readObject() != null){
kontext = (Kontext) inContext.readObject();
}
}
catch(Exception e){
Log.e(TAG, "startContextListener(): " + e.toString());
}
}
}.start();
}
This is usually a result of read(2) on invalid socket descriptor ([EBADF] fildes is not a valid file or socket descriptor open for reading) so it looks that some layer of the app is closing the socket. Can you post more code to demonstrate how you work with the socket?

Categories

Resources