I'm sort of new to Android application development. I already created a very simple application that turns the device's flashlight on/off.
I'd like to try and create a messaging application where you can chat with your friends when both of you are connected to a Wifi. Sort of like "WhatsApp", "Viber", etc..
I would be really happy if you could give me guidelines and help me get the idea of how to develop such an application.
Thank you so much,
Orel.
For that you need to create server program, that will authenticate username & password and communication between diff users.., etc, and you need to send the response based on the user query.
For any network communication application consists of two components:
Server
Client
In the case of WhatsApp android app,its a client application which communicate's with the WhatsApp server.
The server with exchange the data from one client to another client, the client may be desktop, android mobile, iPhone,...etc
Generally chat programs will implemented using sockets, and its depends upon the architecture and technologies which you will chose.
Using this:
ChatServerSide
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ChatServerSide extends Activity implements View.OnClickListener {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
Button btnSendMsg;
EditText etInputMessage;
TextView tvOutputMessage;
TextView tvMyIp;
Socket socket;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_main_activity);
iniUi();
iniListener();
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
tvMyIp.setText("Waiting devices on " + getIpAddress());
}
private void iniUi() {
tvMyIp = (TextView) findViewById(R.id.tvMyIp);
btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
etInputMessage = (EditText) findViewById(R.id.etInputMesage);
tvOutputMessage = (TextView) findViewById(R.id.tvOutputMessage);
}
private void iniListener() {
btnSendMsg.setOnClickListener(this);
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onClick(View view) {
try {
String str = etInputMessage.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true
);
tvOutputMessage.setText(tvOutputMessage.getText().toString() + "You Says: " + str + "\n");
etInputMessage.setText("");
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
String read = null;
try {
read = input.readLine();
if (read == null) {
read = "Client has leave the chat";
socket.close();
updateConversationHandler.post(new updateUIThread(read));
break;
}
updateConversationHandler.post(new updateUIThread("Client Says: " + read));
}catch(IOException e){
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
tvOutputMessage.setText(tvOutputMessage.getText().toString() + msg + "\n");
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
ChatClientSide
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClientSide extends Activity implements View.OnClickListener {
private Handler handler = new Handler();
private Socket socket;
Button btnSendMsg;
EditText etInputMessage;
TextView tvOutputMessage;
Handler updateConversationHandler;
TextView tvMyIp;
private static final int SERVERPORT = 6000;
private static String SERVER_IP = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_main_activity);
iniUi();
iniListener();
SERVER_IP = ActivityMain.ipToConnect;
updateConversationHandler = new Handler();
receiveMsg();
}
#Override
protected void onStop() {
super.onStop();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getServerIp(Intent intent) {
Bundle bundle = intent.getExtras();
String ip = bundle.getString("destAdress");
tvMyIp.setText("Is connected to " + ip);
return ip;
}
private void iniUi() {
tvMyIp = (TextView) findViewById(R.id.tvMyIp);
btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
etInputMessage = (EditText) findViewById(R.id.etInputMesage);
tvOutputMessage = (TextView) findViewById(R.id.tvOutputMessage);
}
private void iniListener() {
btnSendMsg.setOnClickListener(this);
}
#Override
public void onClick(View view) {
try {
String str = etInputMessage.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true
);
tvOutputMessage.setText(tvOutputMessage.getText().toString() + "You Says: " + str + "\n");
etInputMessage.setText("");
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void receiveMsg() {
new Thread(new Runnable() {
#Override
public void run() {
final String host = SERVER_IP;
BufferedReader in = null;
try {
socket = new Socket(host, SERVERPORT);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
String msg = null;
try {
msg = in.readLine();
//msgList.add(msg);
} catch (IOException e) {
e.printStackTrace();
}
if (msg == null) {
break;
} else {
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg) {
final String mssg = msg;
handler.post(new Runnable() {
#Override
public void run() {
tvOutputMessage.setText(tvOutputMessage.getText().toString() + "Server Says: " + mssg + "\n");
}
});
}
}
chat_main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvMyIp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btnSendMsg"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="send"
android:layout_weight="0" />
<EditText
android:id="#+id/etInputMesage"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/tvOutputMessage"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</TextView>
</LinearLayout>
</LinearLayout>
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
i have two application that i am trying to connect using sockets i am trying to test it but the problem is that it only works when i am using the same wifi connection on the phone. one phone has the client and the other on has the server. my question is how do i connect it when they not on the same wifi network
This is the client
package com.example.androidclient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonClear = (Button)findViewById(R.id.clear);
textResponse = (TextView)findViewById(R.id.response);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonClear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
textResponse.setText("");
}});
}
OnClickListener buttonConnectOnClickListener =
new OnClickListener(){
#Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(
editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} 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 {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
this i the severcode
package com.example.androidserversocket;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
infoip.setText(getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 3333;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
String msgReply = "Hello from Android, you are #" + cnt;
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();
message += "replayed: " + msgReply + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
i got the idea from this site
http://android-er.blogspot.com/2014/02/android-sercerclient-example-server.html
What you really have is communication between two components (activities in this case) the same device. I'm not sure if these two components are part of the same app or are installed separately but that does not matter as they will anyway not work across devices. Your server is simply a socket listener.
To implement device to device communication, you will need an actual server up and running outside of the device that the devices can communicate to (like maybe deploy it on your desktop while you are on wifi and let the devices find it or do the real deal and deploy it on a real server - may cost money). An example app for this can be found at https://github.com/Pirngruber/AndroidIM. The app is written for Android and uses Eclipse type builds but other than that the source code works well - I've used this in the past.
Or you can look into push messaging applications. tutorials for chat applications using Google Cloud messaging library are dime a dozen. While they do not use servers in the sense that we deploy applications, they use google's push system to send and receive messages.
I have made a program to send a message from a client to a server(2 android devices), but the message is not being sent.
Here is the code of the client side application:
package com.example.clientphone;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.*;
public class MainActivity extends ActionBarActivity {
private EditText ipaddress , textfield;
private Button send;
private String ip , message;
private Socket client;
private PrintWriter printwriter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText)findViewById(R.id.editText1);
textfield = (EditText)findViewById(R.id.editText2);
send = (Button) findViewById(R.id.button1);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();// enabling strict mode and setting thread policy
StrictMode.setThreadPolicy(policy);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = textfield.getText().toString();
ip = ipaddress.getText().toString();// getting ip address
textfield.setText(" ");
try {
client = new Socket(ip, 5200);// ip address is entered over here....
printwriter = new PrintWriter(client.getOutputStream() , true);// getting the outputstream
printwriter.write(message);// writing the message
printwriter.flush();// flushing the printwriter
printwriter.close();// closing printwriter
client.close();// closing client
} catch (UnknownHostException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
});
}
}
Here is the code for server side application. I have chosen the port 5200 to connect on. I want the user to enter the IP address of the other device and not keep it hard-coded:
package com.example.serverphone;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;
public class MainActivity extends ActionBarActivity {
TextView message;
private ServerSocket socket;
private Handler UpdateConversationHandler;
Thread ServerThread = null;
public static final int port = 5200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message = (TextView)findViewById(R.id.textView1);
UpdateConversationHandler = new Handler();
this.ServerThread = new Thread(new ServerThread());
this.ServerThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable{
#Override
public void run() {
Socket socket2 = null;
try {
socket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
while(!Thread.currentThread().isInterrupted()){
try {
socket2 = socket.accept();
BufferedReaderThread commThread = new BufferedReaderThread(socket2);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class BufferedReaderThread implements Runnable{
private Socket clientSocket;
private BufferedReader input;
public BufferedReaderThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while(!Thread.currentThread().isInterrupted()){// making sure the thread is not interrupted...
try {
String read = input.readLine();
if(read != null){
UpdateConversationHandler.post(new updateUIConversation(read));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIConversation implements Runnable{
private String msg;
public updateUIConversation(String str){
this.msg = str;
}
#Override
public void run() {
message.setText(message.getText().toString() + msg + "/n");
}
}
}
In your client you are doing network operation on the main thread. Do them in a separate thread. Do not silently supress exceptions and you will see in the log.
new Thread(new Runnable() {
public void run() {
try {
Socket client = new Socket(ip, 5200);
PrintWriter = new PrintWriter(client.getOutputStream() , true);
printwriter.write(message);// writing the message
printwriter.flush();// flushing the printwriter
printwriter.close();// closing printwriter
client.close();// closing client
} catch (Exception x) { Log.e("CLIENT", "Exception " + x); }
}).start();
I had created two android applications connected with sockets. Client sends an image to server and Server displays it. when you touch the image on server, it gets its coordinates,this is working now. what I need is that server sends the coordinates to the client, but I dont know how to send them to client and retrieve them, should I open a new socket ? I have no idea how to do this. Can somebody give me a hand please?
This is my code so far
SERVER
package com.example.serverlate;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.TextView;
public class ServerLate extends Activity {
private ServerSocket serverSocket;
String touchedCoordinates;
Handler updateConversationHandler;
Thread serverThread = null;
private ImageView imageView;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_late);
imageView=(ImageView) findViewById(R.id.imageViewServer);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private DataInputStream input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
InputStream in = this.clientSocket.getInputStream();
this.input = new DataInputStream(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
byte[] data;
int len= this.input.readInt();
data = new byte[len];
if (len > 0) {
this.input.readFully(data,0,data.length);
}
updateConversationHandler.post(new updateUIThread(data));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private byte[] byteArray;
public updateUIThread(byte[] array){
this.byteArray=array;
}
#Override
public void run() {
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray , 0, byteArray .length);
imageView.setImageBitmap(bitmap);
imageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
touchedCoordinates="Touch coordinates : " +
String.valueOf(event.getX()) + " x " + String.valueOf(event.getY());
return true;
}
});
}
}
}
CLIENT
package com.example.clientlate;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
public class ClientLate extends Activity {
private Socket socket;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.0.2.2";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_late);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
ImageView imageView=(ImageView) findViewById(R.id.imageView1);
Bitmap bmp=((BitmapDrawable)imageView.getDrawable()).getBitmap();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] array = bos.toByteArray();
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(array.length);
dos.write(array, 0, array.length);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
You can try something like this in client side :
public class ClientLate extends Activity {
public void onCreate(Bundle savedInstanceState) {
....
updateConversationHandler = new Handler();
FPSHandler = new Handler();
new Thread(new ClientThread()).start();
....
}
class ClientThread implements Runnable {
#Override
public void run() {
thread1=Thread.currentThread();
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socketTE = new Socket(serverAddr, SERVERPORT);
CommunicationThread commThread = new CommunicationThread(socketTE);
new Thread(commThread).start();
} catch (UnknownHostException e1) {
Toast.makeText(getApplicationContext(), "Connection failed",
Toast.LENGTH_SHORT).show();
finish();
} catch (IOException e1) {
Toast.makeText(getApplicationContext(), "Connection failed",
Toast.LENGTH_SHORT).show();
finish();
}
}
}
class CommunicationThread implements Runnable
{
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket)
{
thread2=Thread.currentThread();
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
while (running.get())
{
try
{
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable
{
private String msg;
public updateUIThread(String str)
{
this.msg = str;
}
#Override
public void run()
{
...
}
}
....
}
I have a working messaging app that sends messages from the client to the server.
I want the client to CONSTANTLY listen for messages from the server.
I want the client to only send packets to the server when "Start" is called, but the problem is that I have to press it twice for the message to actually deliver to the server (Idk why)
Later on I'll change the program to something that always delivers messages to the server (his GPS location), so I would also like some tips about how to make a loop in an Android app.
//Client
package com.example.clienttest;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Thread m_objThreadClient;
Socket clientSocket;
TextView serverMessage;
EditText clientMessage;
String sIn, sOut;
BufferedReader brOut, brIn;
DataOutputStream oos;
DataInputStream ois;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverMessage = (TextView) findViewById(R.id.textView1);
clientMessage = (EditText) findViewById(R.id.editText1);
m_objThreadClient = new Thread( new Runnable(){
public void run()
{
try {
clientSocket = new Socket("192.168.1.102", 4000);
oos = new DataOutputStream (clientSocket.getOutputStream());
ois = new DataInputStream (clientSocket.getInputStream());
brIn = new BufferedReader (new InputStreamReader(ois));
} catch (IOException e) {
serverMessage.setText(e.getMessage());
}
}
});
m_objThreadClient.start();
}
public void Listener(){
try {
while ((sIn = brIn.readLine()) != null){
sIn = brIn.readLine();
}
serverMessage.setText(sIn);
} catch (IOException e) {
serverMessage.setText(e.getMessage());
}
}
public void Start(View view) {
sOut = clientMessage.getText().toString();
try {
oos.writeUTF(sOut);
oos.flush();
oos.flush();
} catch (IOException e) {
serverMessage.setText(e.getMessage());
}
}
public void onStop(){
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//Server
import java.net.ServerSocket;
import java.net.Socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.Hashtable;
public class Server2 {
#SuppressWarnings("resource")
public static void main (String[] args) throws IOException {
ServerSocket server = null;
try {
server = new ServerSocket(4000);
} catch (IOException e) {
System.err.println("Could not start up on: " + "4000" + "Maby server is already open? Or a portforwording messup?");
System.err.println(e);
System.exit(1);
}
Socket client = null;
while(true) {
try {
client = server.accept();
System.out.print("Connected ");
} catch (IOException e) {
System.err.println("Accept failed.");
System.err.println(e);
}
Thread t = new Thread(new ClientConn(client));
t.start();
}
}
}
class ClientConn implements Runnable {
private Socket client;
String Recv;
DataInputStream inFromClient;
DataOutputStream outToClient;
ClientConn(Socket client) {
this.client = client;
try {
inFromClient = new DataInputStream(client.getInputStream());
outToClient = new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
String response;
try {
while ((response = inFromClient.readUTF()) != null) {
Recv = inFromClient.readUTF();
System.out.print("Msg: " + Recv + " \n");
if( Recv.equals("Hi")){
outToClient.writeUTF("Wa alaikum");
outToClient.flush();
}
else{
outToClient.writeUTF("..what?");
outToClient.flush();
}
}
} catch (IOException e) {
System.out.print("No input ");
System.err.println(e);
}
}
}
I'm building a very small app to send data from the cellphone to a computer. I've read a couple of examples and got the server and client code working. But when i try to connect them, got a "network unreachable" error. Any idea what am i doing wrong??
This is the Server Code:
import java.net.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Server {
static BufferedReader in = null;
static Socket clientSocket = null;
static ServerSocket serverSocket = null;
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("FrameDemo");
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
try {
if (in != null)
in.close();
if (serverSocket.isClosed())
{}
else
serverSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
JLabel Label = new JLabel("");
Label.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(Label, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
Label.setText("Empezo");
serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.err.println(e.getMessage());
System.exit(1);
}
Integer puerto = serverSocket.getLocalPort();
Label.setText("<html>Puerto Abierto: " + puerto.toString() + "<br>IP Servidor: " + serverSocket.getInetAddress().toString() + "</html>");
clientSocket = null;
try {
clientSocket = serverSocket.accept();
Label.setText("Conection Accepted");
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
while ((in.readLine()) != null) {
System.out.println("Mensaje: " + in.readLine());
}
}
}
And the Cliente part
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class PruebaSocket extends Activity {
/** Called when the activity is first created. */
Socket Skt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button Enviar =(Button)findViewById(R.id.OK);
Button Salir = (Button)findViewById(R.id.SALIR);
final TextView IP = (TextView)findViewById(R.id.IP);
Skt = new Socket();
Enviar.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
try{
Skt = new Socket("192.168.1.101",4444);
CharSequence errorMessage = "Coneccted";
Toast.makeText(PruebaSocket.this, errorMessage, Toast.LENGTH_SHORT).show();
}
catch(Exception E)
{
CharSequence errorMessage = E.getMessage();
Toast.makeText(PruebaSocket.this, errorMessage, Toast.LENGTH_SHORT).show();
if (Skt.isConnected())
try {
Skt.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
Salir.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
try {
Skt.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
}
}
192.168.1.101 it's the IP of the server.
I don't know much about java sockets but the normal usage of a socket is: create, bind, and put in listen mode (udp) or call .accept() (tcp). I can see Java also has the binding phase - http://download.oracle.com/javase/1.5.0/docs/api/java/net/ServerSocket.html#bind(java.net.SocketAddress, int).