How to create server to use chat room realtime (SignalR) in android - android

I am beginner in android xamarin. I want to use chat room realtime using SignalR. But i dont know what is "http://10.0.2.2:8081/echo" mean in this example. Is it a server???There are something in that server - like php file, database or something else???
hope your answer, thanks :D or anybody show me how to build a group chat application, please(use socket like :http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-1/ or SignalR in xamarin )
using System.Collections.Generic;
using Android.App;
using Android.OS;
using Android.Widget;
namespace SignalR.Client.MonoDroid.Sample
{
[Activity(Label = "SignalR.Client.MonoDroid.Sample", MainLauncher = true, Icon = "#drawable/icon")]
public class DemoActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
var messageListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, new List<string>());
var messageList = FindViewById<ListView>(Resource.Id.Messages);
messageList.Adapter = messageListAdapter;
var connection = new Connection("http://10.0.2.2:8081/echo");
connection.Received += data =>
RunOnUiThread(() => messageListAdapter.Add(data));
var sendMessage = FindViewById<Button>(Resource.Id.SendMessage);
var message = FindViewById<TextView>(Resource.Id.Message);
sendMessage.Click += delegate
{
if (!string.IsNullOrWhiteSpace(message.Text) && connection.State == ConnectionState.Connected)
{
connection.Send("Android: " + message.Text);
RunOnUiThread(() => message.Text = "");
}
};
connection.Start().ContinueWith(task => connection.Send("Android: connected"));
}
}
}

10.0.x.x is a private subnet (http://en.wikipedia.org/wiki/Private_network). In this example then it is talking about you running some kind of server system on your computer on port 8081.

http://10.0.2.2:8081/echo
10.0.2.2 is the ip of your server
8081 is the port on which server listening your request and give response on same port
echo is the automated generate respone which is given to you on every request with same request(String)
public static class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String s;
String red;
String loc;
public MyClientTask(String addr, int port,String msg){
dstAddress = addr;
dstPort = port;
loc=msg;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
ObjectInputStream inputStream=null;
try {
SocketAddress socketAddress = new InetSocketAddress(dstAddress,dstPort);
socket = new Socket();
socket.setTcpNoDelay(true);
socket.setSoTimeout(5000);
socket.connect(socketAddress, 50000);
// socket = new Socket(dstAddress, dstPort);
System.setProperty("http.keepAlive", "false");
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(loc);
///inputStream = new ObjectInputStream(socket.getInputStream());
InputStream is = socket.getInputStream();
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
out.println("");
//response = br.readLine();
try{
while((s=br.readLine())!=null){
red=red+s;
Log.i("server", ""+red);
}
Log.i("server", ""+red);
}catch(Exception ex){
ex.printStackTrace();
}
Log.i("Server response ", "hi"+s);
try {
System.out.println("Read back from server: " + response);
}
catch(Exception e) {
Log.i("Server response ", response+e);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
dataOutputStream.flush();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
res=response;
Log.i("response:", "res"+res);
// Toast.makeText(getApplicationContext(), "hi"+res, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
call this method to send request and get response on your desired place
public void sendtoserver(String msg){
if(isConnectingToInternet()){
servermsg="$loc"+","+ieminumber+","+formattedDate2+","+formattedDate1+","+formattedDate2+","+formattedDate1+","+1+","+lat1+","+"N"+","+lon1+"*";
//10.0.2.2:8081/echo
MyClientTask myClientTask = new MyClientTask(
"10.0.2.2",8081,msg);
myClientTask.execute();
}
}

If you run your app on an emulator and your server runs on the same pc as the emulator then the only way your client app can reach that server is using ip 10.0.2.2 as Google implemented it that way. Meanwhile your computer can have local ip like 192.168.1.12 but your app can not use that. Also the server on the pc is reachable as localhost or 127.0.0.1 by clients running on the same pc. Your app does not run on that pc. Your app runs on the emulator.

Related

How to set a virtual scene image programmatically on android emulator

I have writing some driven tests to a flutter project and there are a barcode scanner functionality which I can test successfully using the virtual scene tool provided by android emulator.
However there are many cases to test regarding to different barcodes. I want to set a specific barcode image on virtual scene to each case. Is it possible?
I found that the value of this image is putted on ~/.android/avd/[emulatorName]/AVD.conf file at virtualscene\posters variable.
virtualscene\posters=#Variant(\0\0\0\b\0\0\0\x2\0\0\0\b\0w\0\x61\0l\0l\0\0\0\n\xff\xff\xff\xff\0\0\0\n\0t\0\x61\0\x62\0l\0\x65\0\0\0\n\xff\xff\xff\xff)
virtualscene\posters=#Variant(\0\0\0\b\0\0\0\x2\0\0\0\b\0w\0\x61\0l\0l\0\0\0\n\ 0\0\0\\\0/\0U\0s\0\x65\0r\0s\0/\0l\0\x65\0o\0n\0\x61\0r\0\x64\0o\0.\0\x61\0r\0m\0\x65\0r\0o\0/\0\x44\0\x65\0s\0k\0t\0o\0p\0/\0J\0\x61\0m\0\x65\0s\0W\0i\0l\0s\0o\0n\0.\0p\0n\0g\0\0\0\n\0t\0\x61\0\x62\0l\0\x65\0\0\0\n\xff\xff\xff\xff)
You can replace the default (global) image located at $ANDROID_SDK_HOME/emulator/resources/poster.png with your poster.png image,
nor change the default pointer by editing the file $ANDROID_SDK_HOME/emulator/resources/Toren1BD.posters.
You can set the virtual scene image to a specified path. And manipulate the target image while testing.
As the Instrumented tests are running on your (virtual) device, it cannot manipulate the host machine files directly. What can be done, (which is an ugly hack) is to start a server on the host, which can be reached from the virtual device with the hosts loop-back "10.0.2.2" address.
This server can manipulate the target files.
If anybody has better solution, please share it!
An example server and client is here.
Server:
import java.io.*;
import java.net.*;
import java.nio.channels.FileChannel;
public class FileManipulatorServer {
public static void main(String args[]) {
int port = 6789;
FileManipulatorServer server = new FileManipulatorServer( port );
server.startServer();
}
// declare a server socket and a client socket for the server
private ServerSocket fileManipulatorServer = null;
private Socket clientSocket = null;
private int port;
public FileManipulatorServer(int port ) {
this.port = port;
}
public void stopServer() {
System.out.println( "Server cleaning up." );
System.exit(0);
}
public void startServer() {
// Try to open a server socket on the given port
// Note that we can't choose a port less than 1024 if we are not
// privileged users (root)
try {
fileManipulatorServer = new ServerSocket(port);
}
catch (IOException e) {
System.out.println(e);
}
System.out.println( "Waiting for connections. Only one connection is allowed." );
// Create a socket object from the ServerSocket to listen and accept connections.
// Use FileManipulatorTask to process the connection.
while ( true ) {
try {
clientSocket = fileManipulatorServer.accept();
FileManipulatorTask task = new FileManipulatorTask(clientSocket, this);
task.run();
}
catch (IOException e) {
System.out.println(e);
}
}
}
}
class FileManipulatorTask {
private BufferedReader is;
private PrintStream os;
private Socket clientSocket;
private FileManipulatorServer server;
public FileManipulatorTask(Socket clientSocket, FileManipulatorServer server) {
this.clientSocket = clientSocket;
this.server = server;
System.out.println( "Connection established with: " + clientSocket );
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
String line;
try {
boolean serverStop = false;
line = is.readLine();
System.out.println( "Received " + line );
saveImageToPoster(line.trim());
os.println("OK");
os.flush();
System.out.println( "Connection closed." );
is.close();
os.close();
clientSocket.close();
if ( serverStop ) server.stopServer();
} catch (IOException e) {
System.out.println(e);
}
}
private void saveImageToPoster(String filename) {
try {
FileChannel src = new FileInputStream("C:\\fullpathtopostercandidates\\"+filename).getChannel();
FileChannel dest = new FileOutputStream("C:\\fullpathtoconfiguredposter\\poster.jpg").getChannel();
dest.transferFrom(src, 0, src.size());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
import java.io.*;
import java.net.*;
public class FileNameSenderClient {
private String hostname = "10.0.2.2";
private int port = 6789;
public void sendFileName(String filename) {
Socket clientSocket = null;
DataOutputStream os = null;
BufferedReader is = null;
try {
clientSocket = new Socket(hostname, port);
os = new DataOutputStream(clientSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + hostname);
}
if (clientSocket == null || os == null || is == null) {
System.err.println( "Something is wrong. One variable is null." );
return;
}
try {
System.out.println("Write to output stream");
os.writeBytes( filename +"\n");
os.flush();
String responseLine = is.readLine();
System.out.println("Server returns: " + responseLine);
os.close();
is.close();
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
Use the FileNameSenderClient from your instrumented test like this.
#Test
public void testQRcodeReadingOK()
{
FileNameSenderClient c = new FileNameSenderClient();
c.sendFileName("QRCode.jpg");
//your code that wants to use the image, like the this:
onView(withId(R.id.load_qr_code)).perform(click());
}

android socket server programming

I want to connect via socket to my android app.but in server side(android app) I get java.net.SocketTimeoutException error and in client side I get java.net.ConnectException: Connection refused: connecterror.
what is my mistake? thank you
server (android app)
public class ServerSocketTask extends AsyncTask<Void, Void, String> {
final StackTraceElement se = Thread.currentThread().getStackTrace()[2];
private String data = null;
#Override
protected String doInBackground(Void... params) {
Log.d(se.getClassName() + "." + se.getMethodName(), "start");
try {
ServerSocket serverSocket = new ServerSocket(8989);
serverSocket.setSoTimeout(50000);
Socket socket = serverSocket.accept();
socket.setKeepAlive(true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int readed = in.read();
Log.d("","readed bytes : "+readed);
String line;
while ((line = in.readLine()) != null){
Log.i("","line : "+ line);
}
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ServerSocketTask.this.data = result;
}
public String getData() {
return data;
}
}
client
public static void main(String[] args) {
int port;
try (Socket socket = new Socket("192.168.240.105", 8989)) {
String customerId = "123";
String requestId = Configuration.getProperty("requestId");
ClientService result = new ClientService();
String makeRequest = result.objectToJson(customerId, requestId);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.write(makeRequest);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
my client can't connect to server and my server wait for connection.
When you construct ServerSocket(8989) you're binding to wildcard address of network interfaces available on android emulator/device.
However both Android emulator and real device has it's own network interface(s) and thus it's it's own IP addresses. Your client program (development machine) IP address is not the same as IP address of android emulator/device. In other words you cannot connect to the socket created in Android app because you're using wrong address.
This answer should guide you on how to find out the address.

Server doesn't seem to receive Client message ANDROID

I am working on a chat client application and I have made a server. I managed to make the client connect to the server, but then when I send a message to the server, there's no reaction from the server.
Here is the part of the code of my server that is not working
class ClientConnect implements Runnable {
private DataInputStream in = null;
private DataOutputStream out = null;
Socket client;
ClientConnect(Socket client) {
try {
this.client = client;
/* obtain an input stream to this client ... */
in = new DataInputStream (client.getInputStream());
/* ... and an output stream to the same client */
setOut(new DataOutputStream (client.getOutputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
String msg, response;
ChatServerProtocol protocol = new ChatServerProtocol(this);
try {
while (true) {
if (in.available() > 0){
msg = in.readUTF();
response = protocol.process(msg);
getOut().writeBytes("SERVER: " + response);
}
}
} catch (IOException e) {
System.err.println(e);
} finally {
// The connection is closed for one reason or another
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendMsg(String msg) {
try {
getOut().writeBytes(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public DataOutputStream getOut() {
return out;
}
public void setOut(DataOutputStream out) {
this.out = out;
}
}
And here is the client :
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String response = null;
EditText nicknameField = (EditText)findViewById(R.id.nicknameField);
EditText passwordField = (EditText)findViewById(R.id.passwordField);
nickname = nicknameField.getText().toString();
password = passwordField.getText().toString();
switch(v.getId()){
case R.id.signin:
new SendMessage(this).execute("SIGNUP " + nickname + " " + password );
break;
case R.id.signup:
new SendMessage(this).execute("SIGNUP " + nickname + " " + password );
break;
}
}
private String onPostExecuteSendMessage() {
return null;
}
public void showMessage(String response) {
Builder builder = new AlertDialog.Builder(this);
builder.setMessage(response);
AlertDialog dialog = builder.create();
dialog.show();
}
public void getClientSocket(Socket client) {
this.client = client;
try {
out = new DataOutputStream (client.getOutputStream());
in = new DataInputStream (client.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public DataOutputStream getOut() {
// TODO Auto-generated method stub
return this.out;
}
public DataInputStream getIn() {
// TODO Auto-generated method stub
return this.in;
}
public void goMenuChat() {
// TODO Auto-generated method stub
Intent intent = new Intent(this, MenuChatActivity.class);
startActivity(intent);
}
}
Also I used an Asynctask to send message from the client :
package client.chatclient;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import android.os.AsyncTask;
public class SendMessage extends AsyncTask<String, String, String> {
private static final String msg_OK = "OK";
private static final String msg_NICK_IN_USE = "NICK IN USE";
private static final String msg_UNKNOWN_CMD = "UNKNOWN CMD";
private static final String msg_INVALID = "INVALID COMMAND";
private static final String msg_SEND_FAILED = "FAILED TO SEND";
private static final String msg_INCORRECT_IDS = "INCORRECT IDS";
private static final String msg_DISCONNECT = "DISCONNECT";
private WeakReference<MainActivity> activity;
private String message;
private String response = "";
private DataOutputStream out;
private DataInputStream in;
public SendMessage(MainActivity act){
super();
activity = new WeakReference<MainActivity>(act);
}
protected String doInBackground(String... message) {
this.message = message[0];
this.out = activity.get().getOut();
this.in = activity.get().getIn();
try {
out.writeBytes(this.message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response = convertStreamToString(this.in);
return response;
}
protected void onPostExecute(String response) {
if ((response == msg_INCORRECT_IDS) || (response == msg_NICK_IN_USE)){
activity.get().showMessage(response);
}
else if (response == msg_OK){
activity.get().goMenuChat();
}
}
private static String convertStreamToString(DataInputStream in) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the BufferedReader
* return null which means there's no more data to read. Each line will
* appended to a StringBuilder and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
I send my message from the client by clicking on a button then it goes to the SendMessage class, and send the message to the server and normally the server should receive my message in the loop "while (true)..." and sends back a response according to the protocol that I've implemented.
I really don't know what is wrong. If you know how to solve this issue or have some solutions, please tell me ! If you want more details, ask me ! :)
Thank you very much !
EDIT:
I instanciated my ClientConnect here
public class ChatServer {
private static int port = 8080;
public static void main (String[] args) throws IOException {
ServerSocket server = new ServerSocket(port); /* start listening on the port */
System.out.println( "Listening on "+ server );
Socket client = null;
while(true) {
try {
client = server.accept();
System.out.println( "Connection from " + client );
/* start a new thread to handle this client */
Thread t = new Thread(new ClientConnect(client));
t.start();
} catch (IOException e) {
System.err.println("Accept failed.");
System.err.println(e);
System.exit(1);
server.close();
}
}
}
}
EDIT: I found where the problem is. I put some log() statements as you said
log.d(null,"beforeconvert")
try {
log.d(null,"convert")
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
log.d(null,"errorconvert")
e.printStackTrace();
}
After that in logcat, it just shows "beforeconvert". I don't really know what the problem is ? while ((line = reader.readLine()) != null) is surely the problem. When I use the debugger step by step in eclipse, it stops at this line and doesn't even go inside the loop.
EDIT : I REALLY don't know why, but when I quit the emulator when running my app, it shows everything.
Listening on ServerSocket[addr=0.0.0.0/0.0.0.0,localport=8080]
Connection from Socket[addr=/127.0.0.1,port=56646,localport=8080]
client connected
msg received
error !
SIGNUP Nickname Password
SIGNUP Nickname Password
msg converted
OK
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at server.ClientConnect.convertStreamToString(ChatServer.java:357)
at server.ClientConnect.run(ChatServer.java:304)
at java.lang.Thread.run(Unknown Source)
java.net.SocketException: Connection reset by peer: socket write error
When you are writing data to output stream in the end you need to flush
this.out.flush();
I think this is why the data is not sent and received
Hope that helps.
Edit:
Let me try to explain in general idea..
When you are opening a socket you have a connection to another machince.
So the
in.available();
and
socket.accpet();
Should work.. once you are writing into outputstream you must flush in order to see the data(or close, i think it flushes before it get closed).
Anyway i attach a link to an example.. You should try this one, Or look at parts you have problem with..
http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/

ServerSocket Android

Hey community I have the following ServerSocket which should listen to port 53000 and log any received data. However, I cannot seem to get past the server.accept() blocking call.
public void run() {
SocketServer server = new ServerSocket(53000);
//---buffer store for the stream---
byte[] buffer = new byte[1024];
//---bytes returned from read()---
int bytes;
//---keep listening to the InputStream until an
// exception occurs---
while (true) {
try {
socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
Log.i("received response from server", str);
in.close();
socket.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e){
server.close();
Log.e(TAG, e.getMessage());
}
}
}
I have also given the application the INTERNET permission in the Manifest file.
()
To add to the mystery, I have also verified client responses get sent to that port.
Is there something in particular I need to do to make this work?
Thanks.
Your code is very messy and won't even compile. I made some adjustments so that i could test your code, and it's working fine. Here is the test application I used:
package com.test.stackoverflow
import java.io.BufferedReader;
public class ServerSocketTestActivity extends Activity {
/** Called when the activity is first created. */
private static String TAG = "ServerSocketTest";
private ServerSocket server;
Runnable conn = new Runnable() {
public void run() {
try {
server = new ServerSocket(53000);
while (true) {
Socket socket = server.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
Log.i("received response from server", str);
in.close();
socket.close();
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(conn).start();
}
#Override
protected void onPause() {
super.onPause();
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Using this code and netcat running via adb shell I was able to connect and communicate with the application.
When working with The Client Declare these methods
To access Streams
// gets the input stream // ObjectInputStream input;
// gets the output stream // ObjectOutputStream output;
// ServerSocket server;
// Socket connection;
maybe you have a another class to access the socket;
server = new ServerSocket(5001, 100);
// step 1 create socket connection
server = new ServerSocket(5001, 100);
while(the condition is true)
// step 2 wait for connection
// step 3 get streams
// step 4 : process the connection
// step 5 : close connection

Android TCP Client in phone has problems in communicating with external server

I have a TCP Client in Android (Java program in Eclipse). The server was another Java app running in Eclipse. Everything works fine in this situation.
When I tried to receive message from my colleague's app (developed in Rhapsody and I think C++), I receive the message only after his app is closed and not while his app is running and sending messages. Do you have any idea why this happens?
Thank you for the time and effort on this.
Cheers,
Madhu
The java server is like this:
public class TCPSendServer implements Runnable{
public static final String SERVERIP = "192.168.178.24";
public static final int SERVERPORT = 1200;
//static Category cat = Category.getInstance(TCPSendServer.class.getName());
//cat.debug("Start of main()");
public void run() {
try {
System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
String msg = "<MSG><N>shiftDirection</N><V>1</V></MSG>";
String msg1 = "<MSG><N>vehicleSpeed</N><V>120</V></MSG>";
String msg2 = "SD<!N><V>0<!V><!MSG>";
//while (true) {
Socket client = serverSocket.accept();
try {
System.out.println("S: Sending: '" + msg + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(client.getOutputStream())),true);
Thread.sleep (5000);
out.println(msg);
Thread.sleep (5000);
//out.println(msg2);
Thread.sleep (5000);
out.println(msg1);
//out.flush();
System.out.println("S: Sent.");
System.out.println("S: Done.");
} catch(Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} //finally {
// client.close();
//}
//}
} catch (Exception e) {
System.out.println("S: First try error");
e.printStackTrace();
}
}
public static void main (String a[]) {
Thread desktopServerThread = new Thread(new TCPSendServer());
desktopServerThread.start();
}
}
The Android client code:
Main activity:
public class TCPListen extends Activity implements TCPListener {
private TextView mTitle;
public String data[] = new String[2];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
//TcpServiceHandler handler=new TcpServiceHandler(this);
//handler.execute("192.168.178.24");
TcpServiceHandler handler = new TcpServiceHandler(this,this);
Thread th = new Thread(handler);
th.start();
}
public String[] callCompleted(String source){
Log.d("TCP", "Std parser " + source);
mTitle.setText(source);
//String data[] = new String[2];
//if (source.matches("<MSG><N>.*</N><V>.*</V></MSG>")) {
Document doc = null;
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = (Document) db.parse(new ByteArrayInputStream(source.getBytes()));
NodeList n = doc.getElementsByTagName("N");
Node nd = n.item(0);
String msgName = nd.getFirstChild().getNodeValue();
NodeList n1 = doc.getElementsByTagName("V");
Node nd1 = n1.item(0);
String tmpVal = nd1.getFirstChild().getNodeValue();
data[0] = msgName;
data[1] = tmpVal;
Log.d("TCP", "Inside Std parser " + data[0] + " " + data[1]);
//actionOnData(data[0], data[1]);
}
catch(Exception e){
e.printStackTrace();
}
Log.d("TCP", "Just outside Std parser " + data[0] + " " + data[1]);
return data;
//} else Log.d("TCP", "Message in wrong format " + source);
//mTitle.setText("Message in wrong format " + source);
//return data;
}
Interface:
public interface TCPListener {
public String[] callCompleted(String msg);
}
TCPServiceHandler:
public class TcpServiceHandler implements Runnable {
TCPListener _listener;
private Activity _act;
public TcpServiceHandler(TCPListener listener, Activity act){
_listener = listener;
_act = act;
}
public synchronized void run() {
// TODO Auto-generated method stub
//if(socket==null){
try {
InetAddress serverAddr = InetAddress.getByName("192.168.178.25");
Socket socket = new Socket(serverAddr, 1200);
//
while(true){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final String str = in.readLine();
this._act.runOnUiThread(new Runnable(){
public void run() {
_listener.callCompleted(str);
}
});
}
catch(Exception e){
e.printStackTrace();
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is problem with the SERVERIP here. Are you running your app from an emulator in your local machine? Your emulator is not part of your LAN. Emulator runs behind a virtual router/firewall service that isolates it from your development machine's network interfaces and settings and from the internet.
So you need to use network redirections or port forwarding to achieve communication with the server which is on a separate machine.
If you are running the app on a device then you can make that device as part of your network and then it should work.
There has been a solution, at least for the time being. I use readLine() to read contents of sockets and this expects \n or \r or similar characters until it returns the contents. This was not the issue for me when both server and client were in Java. But when the client had to receive messages from a different app, I faced this problem. It was overcome by just adding \n to the end of message sent by the other app.

Categories

Resources