Using Netty ( tcp ), sending message from client in android to server - android

I successed connection bitween client in android and server.
but, when I want to send message like "hello" or whatever, message was disappear.
this is my client code:
group = new OioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(OioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(handler);
}
});
Channel ch = null;
ChannelFuture f = null;
try {
f = b.connect(new InetSocketAddress(host, port)).sync();
ch = f.channel();
} catch (InterruptedException e) {
e.printStackTrace();
}
ch.writeAndFlush("hello!");
and this is my server code:
#Override
public void channelActive(ChannelHandlerContext ctx){
channels.add(ctx.channel());
ctx.channel().writeAndFlush("Welcome My Server");
System.out.println(ctx.channel().remoteAddress());
}
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf in = (ByteBuf) msg;
try {
while (in.isReadable()) {
System.out.print((char) in.readByte());
System.out.flush();
}
} finally {
ReferenceCountUtil.release(msg);
}
}
when I connect, Server was printing 'connected client ip address'
but after that, 'hello' message is not printed in my server.
what is wrong? server? client?
I think encode, decode is not problem, cuz nothing received
please let me know how to do for that?

If you want to write a String you need to put StringEncoder in the ChannelPipeline (on the client side). If you check the returned ChannelFuture of writeAndFlush(...) you will see it was failed.

Related

Socket Dies When Reestablishing Later

I have a client server model where the client runs on android. It establishes its tls sockets using the following code:.
(Everything the client does to login and relogin)
public class LoginAsync extends AsyncTask<Boolean, String, Boolean>
protected Boolean doInBackground(Boolean... params)
{
try
{
//only handle 1 login request at a time
synchronized(loginLock)
{
if(tryingLogin)
{
Utils.logcat(Const.LOGW, tag, "already trying a login. ignoring request");
onPostExecute(false);
return false;
}
tryingLogin = true;
}
//http://stackoverflow.com/a/34228756
//check if server is available first before committing to anything
// otherwise this process will stall. host not available trips timeout exception
Socket diag = new Socket();
diag.connect(new InetSocketAddress(Vars.serverAddress, Vars.commandPort), TIMEOUT);
diag.close();
//send login command
Vars.commandSocket = Utils.mkSocket(Vars.serverAddress, Vars.commandPort, Vars.expectedCertDump);
String login = Utils.currentTimeSeconds() + "|login|" + uname + "|" + passwd;
Vars.commandSocket.getOutputStream().write(login.getBytes());
//read response
byte[] responseRaw = new byte[Const.BUFFERSIZE];
int length = Vars.commandSocket.getInputStream().read(responseRaw);
//on the off chance the socket crapped out right from the get go, now you'll know
if(length < 0)
{
Utils.logcat(Const.LOGE, tag, "Socket closed before a response could be read");
onPostExecute(false);
return false;
}
//there's actual stuff to process, process it!
String loginresp = new String(responseRaw, 0, length);
Utils.logcat(Const.LOGD, tag, loginresp);
//process login response
String[] respContents = loginresp.split("\\|");
if(respContents.length != 4)
{
Utils.logcat(Const.LOGW, tag, "Server response imporoperly formatted");
onPostExecute(false); //not a legitimate server response
return false;
}
if(!(respContents[1].equals("resp") && respContents[2].equals("login")))
{
Utils.logcat(Const.LOGW, tag, "Server response CONTENTS imporperly formated");
onPostExecute(false); //server response doesn't make sense
return false;
}
long ts = Long.valueOf(respContents[0]);
if(!Utils.validTS(ts))
{
Utils.logcat(Const.LOGW, tag, "Server had an unacceptable timestamp");
onPostExecute(false);
return false;
}
Vars.sessionid = Long.valueOf(respContents[3]);
//establish media socket
Vars.mediaSocket = Utils.mkSocket(Vars.serverAddress, Vars.mediaPort, Vars.expectedCertDump);
String associateMedia = Utils.currentTimeSeconds() + "|" + Vars.sessionid;
Vars.mediaSocket.getOutputStream().write(associateMedia.getBytes());
Intent cmdListenerIntent = new Intent(Vars.applicationContext, CmdListener.class);
Vars.applicationContext.startService(cmdListenerIntent);
onPostExecute(true);
return true;
}
catch (CertificateException c)
{
Utils.logcat(Const.LOGE, tag, "server certificate didn't match the expected");
onPostExecute(false);
return false;
}
catch (Exception i)
{
Utils.dumpException(tag, i);
onPostExecute(false);
return false;
}
}
with the mksocket utility function being:
public static Socket mkSocket(String host, int port, final String expected64) throws CertificateException
{
TrustManager[] trustOnlyServerCert = new TrustManager[]
{new X509TrustManager()
{
#Override
public void checkClientTrusted(X509Certificate[] chain, String alg)
{
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String alg) throws CertificateException
{
//Get the certificate encoded as ascii text. Normally a certificate can be opened
// by a text editor anyways.
byte[] serverCertDump = chain[0].getEncoded();
String server64 = Base64.encodeToString(serverCertDump, Base64.NO_PADDING & Base64.NO_WRAP);
//Trim the expected and presented server ceritificate ascii representations to prevent false
// positive of not matching because of randomly appended new lines or tabs or both.
server64 = server64.trim();
String expected64Trimmed = expected64.trim();
if(!expected64Trimmed.equals(server64))
{
throw new CertificateException("Server certificate does not match expected one.");
}
}
#Override
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
}
};
try
{
SSLContext context;
context = SSLContext.getInstance("TLSv1.2");
context.init(new KeyManager[0], trustOnlyServerCert, new SecureRandom());
SSLSocketFactory mkssl = context.getSocketFactory();
Socket socket = mkssl.createSocket(host, port);
socket.setKeepAlive(true);
return socket;
}
catch (Exception e)
{
dumpException(tag, e);
return null;
}
}
Here is the command listener service that gets started on successful login:
public class CmdListener extends IntentService
protected void onHandleIntent(Intent workIntent)
{
// don't want this to catch the login resposne
Utils.logcat(Const.LOGD, tag, "command listener INTENT SERVICE started");
while(inputValid)
{
String logd = ""; //accumulate all the diagnostic message together to prevent multiple entries of diagnostics in log ui just for cmd listener
try
{//the async magic here... it will patiently wait until something comes in
byte[] rawString = new byte[Const.BUFFERSIZE];
int length = Vars.commandSocket.getInputStream().read(rawString);
if(length < 0)
{
throw new Exception("input stream read failed");
}
String fromServer = new String(rawString, 0, length);
String[] respContents = fromServer.split("\\|");
logd = logd + "Server response raw: " + fromServer + "\n";
//check for properly formatted command
if(respContents.length != 4)
{
Utils.logcat(Const.LOGW, tag, "invalid server response");
continue;
}
//verify timestamp
long ts = Long.valueOf(respContents[0]);
if(!Utils.validTS(ts))
{
Utils.logcat(Const.LOGW, tag, "Rejecting server response for bad timestamp");
continue;
}
//just parse and process commands here. not much to see
}
catch (IOException e)
{
Utils.logcat(Const.LOGE, tag, "Command socket closed...");
Utils.dumpException(tag, e);
inputValid = false;
}
catch(NumberFormatException n)
{
Utils.logcat(Const.LOGE, tag, "string --> # error: ");
}
catch(NullPointerException n)
{
Utils.logcat(Const.LOGE, tag, "Command socket null pointer exception");
inputValid = false;
}
catch(Exception e)
{
Utils.logcat(Const.LOGE, tag, "Other exception");
inputValid = false;
}
}
//only 1 case where you don't want to restart the command listener: quitting the app.
//the utils.quit function disables BackgroundManager first before killing the sockets
//that way when this dies, nobody will answer the command listener dead broadcast
Utils.logcat(Const.LOGE, tag, "broadcasting dead command listner");
try
{
Intent deadBroadcast = new Intent(Const.BROADCAST_BK_CMDDEAD);
sendBroadcast(deadBroadcast);
}
catch (Exception e)
{
Utils.logcat(Const.LOGE, tag, "couldn't broadcast dead command listener... leftover broadacast from java socket stupidities?");
Utils.dumpException(tag, e);
}
}
And here is the background manager that signs you in when you switch from wifi to lte, lte to wifi, or when you come out of the subway from nothing to lte:
public class BackgroundManager extends BroadcastReceiver
{
private static final String tag = "BackgroundManager";
#Override
public void onReceive(final Context context, Intent intent)
{
if(Vars.applicationContext == null)
{
//sometimes intents come in when the app is in the process of shutting down so all the contexts won't work.
//it's shutting down anyways. no point of starting something
return;
}
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if(Vars.uname == null || Vars.passwd == null)
{
//if the person hasn't logged in then there's no way to start the command listener
// since you won't have a command socket to listen on
Utils.logcat(Const.LOGW, tag, "user name and password aren't available?");
}
String action = intent.getAction();
if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
{
manager.cancel(Vars.pendingRetries);
new KillSocketsAsync().execute();
if(Utils.hasInternet())
{
//internet reconnected case
Utils.logcat(Const.LOGD, tag, "internet was reconnected");
new LoginAsync(Vars.uname, Vars.passwd).execute();
}
else
{
Utils.logcat(Const.LOGD, tag, "android detected internet loss");
}
//command listener does a better of job of figuring when the internet died than android's connectivity manager.
//android's connectivity manager doesn't always get subway internet loss
}
else if (action.equals(Const.BROADCAST_BK_CMDDEAD))
{
String loge = "command listener dead received\n";
//cleanup the pending intents and make sure the old sockets are gone before making new ones
manager.cancel(Vars.pendingRetries);
new KillSocketsAsync().execute(); //make sure everything is good and dead
//all of this just to address the stupid java socket issue where it might just endlessly die/reconnect
//initialize the quick dead count and timestamp if this is the first time
long now = System.currentTimeMillis();
long deadDiff = now - Vars.lastDead;
Vars.lastDead = now;
if(deadDiff < Const.QUICK_DEAD_THRESHOLD)
{
Vars.quickDeadCount++;
loge = loge + "Another quick death (java socket stupidity) occured. Current count: " + Vars.quickDeadCount + "\n";
}
//with the latest quick death, was it 1 too many? if so restart the app
//https://stackoverflow.com/questions/6609414/how-to-programatically-restart-android-app
if(Vars.quickDeadCount == Const.QUICK_DEAD_MAX)
{
loge = loge + "Too many quick deaths (java socket stupidities). Restarting the app\n";
Utils.logcat(Const.LOGE, tag, loge);
//self restart, give it a 5 seconds to quit
Intent selfStart = new Intent(Vars.applicationContext, InitialServer.class);
int pendingSelfId = 999;
PendingIntent selfStartPending = PendingIntent.getActivity(Vars.applicationContext, pendingSelfId, selfStart, PendingIntent.FLAG_CANCEL_CURRENT);
manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+Const.RESTART_DELAY, selfStartPending);
//hopefully 5 seconds will be enough to get out
Utils.quit();
return;
}
else
{ //app does not need to restart. still record the accumulated error messages
Utils.logcat(Const.LOGE, tag, loge);
}
//if the network is dead then don't bother
if(!Utils.hasInternet())
{
Utils.logcat(Const.LOGD, tag, "No internet detected from commnad listener dead");
return;
}
new LoginAsync(Vars.uname, Vars.passwd).execute();
}
else if (action.equals(Const.ALARM_ACTION_RETRY))
{
Utils.logcat(Const.LOGD, tag, "login retry received");
//no point of a retry if there is no internet to try on
if(!Utils.hasInternet())
{
Utils.logcat(Const.LOGD, tag, "no internet for sign in retry");
manager.cancel(Vars.pendingRetries);
return;
}
new LoginAsync(Vars.uname, Vars.passwd).execute();
}
else if(action.equals(Const.BROADCAST_LOGIN_BG))
{
boolean ok = intent.getBooleanExtra(Const.BROADCAST_LOGIN_RESULT, false);
Utils.logcat(Const.LOGD, tag, "got login result of: " + ok);
Intent loginResult = new Intent(Const.BROADCAST_LOGIN_FG);
loginResult.putExtra(Const.BROADCAST_LOGIN_RESULT, ok);
context.sendBroadcast(loginResult);
if(!ok)
{
Utils.setExactWakeup(Const.RETRY_FREQ, Vars.pendingRetries);
}
}
}
}
The server is on a select system call to listen to its established sockets. It accepts new sockets using this code (C on Linux)
incomingCmd = accept(cmdFD, (struct sockaddr *) &cli_addr, &clilen);
if(incomingCmd < 0)
{
string error = "accept system call error";
postgres->insertLog(DBLog(Utils::millisNow(), TAG_INCOMINGCMD, error, SELF, ERRORLOG, DONTKNOW, relatedKey));
perror(error.c_str());
goto skipNewCmd;
}
string ip = inet_ntoa(cli_addr.sin_addr);
//setup ssl connection
SSL *connssl = SSL_new(sslcontext);
SSL_set_fd(connssl, incomingCmd);
returnValue = SSL_accept(connssl);
//in case something happened before the incoming connection can be made ssl.
if(returnValue <= 0)
{
string error = "Problem initializing new command tls connection from " + ip;
postgres->insertLog(DBLog(Utils::millisNow(), TAG_INCOMINGCMD, error, SELF, ERRORLOG, ip, relatedKey));
SSL_shutdown(connssl);
SSL_free(connssl);
shutdown(incomingCmd, 2);
close(incomingCmd);
}
else
{
//add the new socket descriptor to the client self balancing tree
string message = "new command socket from " + ip;
postgres->insertLog(DBLog(Utils::millisNow(), TAG_INCOMINGCMD, message, SELF, INBOUNDLOG, ip, relatedKey));
clientssl[incomingCmd] = connssl;
sdinfo[incomingCmd] = SOCKCMD;
failCount[incomingCmd] = 0;
}
The problem I'm having is when the client reconnects to the server from an ip address it has used recently, the socket on the client always seems to die after creation. If I retry again, it dies again. The only way to get it to connect is for the android app to kill and restart itself.
Example: on wifi at home with address 192.168.1.101. Connection ok. Switch to LTE on address 24.157.18.90. Reconnects me to the server ok. Come back home and get 192.168.1.101. The socket always dies until the app kills itself. Or if while I'm outside, I loose LTE because I take the subway, when I come out, I get the same problem. Note that each time, it will make a new socket. It will not somehow try to salvage the old one. The socket creation also seems to succeed. It's just as soon as the client wants to do a read on it, java says the socket is closed.
I put all the relevant code in its unobfuscated original form since it's my hobby project. I am out of ideas why this happens.
// http://stackoverflow.com/a/34228756
//check if server is available first before committing to anything
// otherwise this process will stall. host not available trips timeout exception
Socket diag = new Socket();
diag.connect(new InetSocketAddress(Vars.serverAddress, Vars.commandPort), TIMEOUT);
diag.close();
It is caused by these three pointless lines of code. The server gets a connection and an immediate read() result of zero.
There is no value in establishing a connection only to close it and then assume you can open another one. You should use the conection you just established. In general the correct way to establish whether any resource is available is to try to use it in the normal way. Techniques like the above are indistinguishable from attempts to predict the future.

SignalR HTTP status 400 multiple clients

I'm running an application with SignalR 2.2.0 on server side and signalr-java-client (self compiled, last GitHub version) on Android as client.
Currently, there are 4 clients connected to my hub. From time to time, it happens, that all 4 clients simultaneously receive the HTTP status 400 with the message "The connection id is in the incorrect format" (the clients were connected before). I analyzed this multiple times and am not able to find any information/pattern when or why this happens.
The connecten is secured via JWT, the token is definitely valid. When retrieving a new token, the connection is stopped and started again. Apart from this, it is very unlikely that the error is device-related, because the error is thrown at all 4 clients the same time.
I know, this error can occur when the client's Identity changes, but an Identity change for 4 clients the same time seems very unlikely to me.
This is the server-code used for authentication (Deepak asked).
The following method gets called in my Startup.cs:
public static void ConfigureOAuth(IAppBuilder app, string audienceID, string sharedSecret)
{
byte[] secret = TextEncodings.Base64Url.Decode(sharedSecret);
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
Provider = new MyOAuthBearerAuthenticationProvider(),
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audienceID },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(Issuer, secret)
}
});
}
Here's the code of MyOAuthBearerAuthenticationProvider class:
class MyOAuthBearerAuthenticationProvider : OAuthBearerAuthenticationProvider
{
/// <summary>
/// Get's a JWT from querysting and puts it to context
/// </summary>
public override Task RequestToken(OAuthRequestTokenContext context)
{
if (context.Token == null)
{
string value = context.Request.Query.Get("auth_token");
if (!string.IsNullOrEmpty(value)) //token from queryString
{
context.Token = value;
}
}
return Task.FromResult<object>(null);
}
}
I have to retrieve the token from query string, because additionally to the java-client, a javascript client is used, which is not able to set headers.
Lastly, I secure my hub and some of it's methods with the Authorization attribute:
[Authorize(Roles = "MyExampleRole")]
This is the client-code for connection:
public boolean connect(String url, String token) {
if (connected) {
return true;
}
try {
this.hubConnection = new HubConnection(url, "auth_token=" + token, true, logger);
this.hubProxy = hubConnection.createHubProxy("MyHub");
this.hubProxy.subscribe(this.signalRMethodProvider);
this.hubConnection.stateChanged(stateChangedCallback);
SignalRFuture<Void> awaitConnection = this.hubConnection.start();
awaitConnection.get(10000, TimeUnit.MILLISECONDS);
return true;
}
catch (InterruptedException | TimeoutException | ExecutionException e) {
log.error("connect", e);
return false;
}
}
Does anybody have an Idea, how to fix this problem or where I may receive further information?
Thank you very much
-Lukas
seems fine...
possible alteration you can do is change
awaitConnection.get(10000, TimeUnit.MILLISECONDS);
to
awaitConnection.done(new Action<Void>() {
#Override
public void run(Void obj) throws Exception {
Log.d(TAG, "Hub Connected");
}
}).onError(new ErrorCallback() {
#Override
public void onError(Throwable error) {
error.printStackTrace();
Log.d(TAG, "SignalRServiceHub Cancelled");
}
}).onCancelled(new Runnable() {
#Override
public void run() {
Log.d(TAG, "SignalRServiceHub Cancelled");
}
});

How to create and send Bye message from client to server in jainsip android?

I have tried jainsip example in Mobicents restcomm-android-sdk.Its worked for me but i am not able create bye message from client side properly.
I created a Bye Message class like this
public class Bye {
public Request MakeRequest(SipManager sipManager) throws ParseException,
InvalidArgumentException {
AddressFactory addressFactory = sipManager.addressFactory;
SipProvider sipProvider = sipManager.sipProvider;
MessageFactory messageFactory = sipManager.messageFactory;
HeaderFactory headerFactory = sipManager.headerFactory;
// Create addresses and via header for the request
Address fromAddress = addressFactory.createAddress("sip:"
+ sipManager.getSipProfile().getSipUserName() + "#"
+ sipManager.getSipProfile().getRemoteIp());
fromAddress.setDisplayName(sipManager.getSipProfile().getSipUserName());
Address toAddress = addressFactory.createAddress("sip:"
+ sipManager.getSipProfile().getSipUserName() + "#"
+ sipManager.getSipProfile().getRemoteIp());
toAddress.setDisplayName(sipManager.getSipProfile().getSipUserName());
Address contactAddress = sipManager.createContactAddress();
ArrayList<ViaHeader> viaHeaders = sipManager.createViaHeader();
URI requestURI = addressFactory.createAddress(
"sip:" + sipManager.getSipProfile().getRemoteEndpoint())
.getURI();
// Build the request
CallIdHeader callIdHeader = sipManager.sipProvider.;
final Request request = messageFactory.createRequest(requestURI,
Request.BYE, sipProvider.getNewCallId(),
headerFactory.createCSeqHeader(1l, Request.BYE),
headerFactory.createFromHeader(fromAddress, "c3ff411e"),
headerFactory.createToHeader(toAddress, null), viaHeaders,
headerFactory.createMaxForwardsHeader(70));
// Add the contact header
request.addHeader(headerFactory.createContactHeader(contactAddress));
ExpiresHeader eh = headerFactory.createExpiresHeader(300);
request.addHeader(eh);
// Print the request
System.out.println(request.toString());
return request;
// Send the request --- triggers an IOException
// sipProvider.sendRequest(request);
// ClientTransaction transaction = sipProvider
// .getNewClientTransaction(request);
// Send the request statefully, through the client transaction.
// transaction.sendRequest();
}
}
Call it From SipManager class as
public void disconnectCall() throws NotInitializedException {
// TODO Auto-generated method stub
if (!initialized)
throw new NotInitializedException("Sip Stack not initialized");
this.sipManagerState = SipManagerState.BYE;
Bye byeRequest = new Bye();
Request r=null ;
try{
r = byeRequest.MakeRequest(this);//byeRequest.MakeRequest(SipManager.this);
final ClientTransaction transaction = this.sipProvider
.getNewClientTransaction(r);
Thread thread = new Thread() {
public void run() {
try {
transaction.sendRequest();
} catch (SipException e) {
e.printStackTrace();
}
}
};
thread.start();
} catch (TransactionUnavailableException e) {
e.printStackTrace();
}catch (InvalidArgumentException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
I have got 481 error code as response.I think I have missed the current callid field in the bye message.I have searched for it but not found from sipmanager class.pls help.
Nidhin,
BYE messages are always inside a SIP dialog, so you don't have to create a new message from scratch. Instead, you just need to get ahold of the dialog you want to terminate, create a request of type BYE from that and send it. JAIN will take care of the rest.
For an example, you can check the code at the Mobicents restcomm-android-sdk repo, method sendByeClient():
https://github.com/Mobicents/restcomm-android-sdk/blob/master/sipua/src/main/java/org/mobicents/restcomm/android/sipua/impl/SipManager.java#L931
Please also keep in mind that the JAIN SIP example has been obsoleted by Messenger example that uses the Restcomm Android Client SDK which offers a simpler API. Here's its code for your reference:
https://github.com/Mobicents/restcomm-android-sdk/tree/master/Examples/restcomm-messenger

Android : Listener for incoming UDP messages?

I have an application android who send data to the server (PC) but I don't receive any data from the PC to the application. And, how can I do a listener for incoming UDP messages ?
because I need an app to be running all the time even if the app is closed. How would I ensure that my 'listener' service is always running?
I would like to receive a notification when a message arrive from the server to the smartphone.
Here is my code :
public class MainActivity extends Activity implements TextWatcher, OnClickListener {
Client client;
EnvoyerMess envoyermessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
client = new Client();
client.execute();
lancer.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
envoyermessage=new EnvoyerMess();
envoyermessage.execute();
}
});
}
class Client extends AsyncTask<Void,Void,String>{
DatagramSocket client;
String test ;
public String doInBackground(Void...params){
String result=null;
int port=4000;
DatagramSocket clientSocket = null;
byte[] receiveData = new byte[256];
DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
try{
InetAddress adresse = InetAddress.getByName("10.0.2.2");
clientSocket = new DatagramSocket(port);
clientSocket.receive(packet);
result = new String(packet.getData());
Log.d("","Received :) ");
}catch (Exception e) {
e.printStackTrace();
} finally {
if (clientSocket != null) {
clientSocket.close();
}
}
return result;
}
public void onPostExecute(String result){
if (result != null) {
//createNotify();
TextView tv = (TextView) MainActivity.this.findViewById(R.id.textView1);
tv.setText(result);
}
}
thanks in advance..
I would start by ensuring that the PC is in fact sending the packets to the correct IP address. Do this by using wireshark, http://www.wireshark.org/ , or a similar tool.
To ensure that your task is running even though the application is is closed you need a service, http://developer.android.com/guide/components/services.html.
Edit:
I you are using an emulator you must first enable redirection in the avd router. This link provides instructions on how to accomplish this developer.android.com/tools/devices/emulator.html#redirection (I cant publish links so you'll have to copy-paste).
If you are developing in windows you would also need to enable telnet. This link describes the steps to accomplish that social.technet.microsoft.com/wiki/contents/articles/910.windows-7-enabling-telnet-client.aspx (again, copy-paste)

android client socket is not receiving data

I have a tcp server which is not in java also its a hardware device , I need to send and receve the data ,
I am connecting with server and sending some configuration data using following code
this.clientSocket=new Socket("198.168.1.17",9999);
this.os=new DataOutputStream(this.clientSocket.getOutputStream());
this.in=new DataInputStream(this.clientSocket.getInputStream());
System.out.println("Conncted");
char data[]={0x03,0x03,0x00};
byte b[]=new byte[data.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) data[i];
}
try {
os.write(b);
Device receives data correctly , now in my tcp client i am not able to receive data , though i write following code just after above code
int size =in.available();
byte data1[]=new byte[size];
// in.read(data1);
String str=new String(data1);
System.out.println("Reading data:"+str);
It only shows reading data , and string has not data
also i tried about code in thread
public void run(){
try{
while(true){
int size =in.available();
byte data[]=new byte[size];
in.read(data);
String str=new String(data);
System.out.println("Reading data:"+str);
}
in thread it only shows reading data ,
Please help how can i get data from the server also please note server is built in i can not change the server code
what available() method do in code "int size =in.available();"????????
Solution may be:
available() method return 0 so you are not able to receive data.
use this code for receiving data from socket. write this code before onCreate.
private EditText mInputMessageView;
private Emitter.Listener onNewMessage = new Emitter.Listener() {
#Override
public void call(final Object... args) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
String message;
try {
username = data.getString("username");
message = data.getString("message");
} catch (JSONException e) {
return;
}
// add the message to view
addMessage(username, message);
}
});
}
};

Categories

Resources