Android client side using Socket |
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);
}
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<EditText
android:id="@+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="dstAddress" />
<EditText
android:id="@+id/port"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="dstPort" />
<Button
android:id="@+id/connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connect..."/>
<Button
android:id="@+id/clear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Clear"/>
<TextView
android:id="@+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Remark: uses-permission of "android.permission.INTERNET" is needed.
Download the files.
Related:
- Node.js server communicate with Android client
*** Updated example: Bi-directional communication between Client and Server, using ServerSocket, Socket, DataInputStream and DataOutputStream.
Works like a charm .... Awesome
ReplyDeletedear andr.oid eric, i created one application where socket programmin g is used, and that application not running on android version 4.0 and later.. i wnat ur help
ReplyDeletethanks for your toturial guys
ReplyDeletehmm... i try to connect android device to server but it didn't well
ReplyDeleteif i try to eclipse emulator instead of android device, it works well
both of them, same situation. only emulator, android device difference
can you answer about my problem??
What can i check to solve this problem?
I am using hyperterminal to pass data to my android phone through wifi the data is being displayed on my phone at a random time and the data is scrambled and lot of extra garbage is also there, pls help!!
ReplyDeleteI can't download the project file. The page doesn't loading.
ReplyDeleteHi...
ReplyDeleteNice tutorial but i can not run it on my phone. How do i run it on my phone? Please help!!!
Thank you for posting this; it worked great on the emulator!
ReplyDeleteI'll be migrating this app to a phone shortly. I'd also like to expand functionality to have indicators that display data sent from the server; do you have any posts on how I could achieve this? I'm new to Android and the site so will be rooting around in the coming days.
Thanks again!
hello..! sir
ReplyDeleteI am new to scripting language.. would you help me to learn this android scripting language by suggesting some useful links.
greet job. working well
ReplyDeleteIts really great, but in case when i don't know about the server ip address then how can i connect with server as a client plzz tell me...!
ReplyDeleteHow can i user it for Instant messaging app in Android? And how to retrive port number from user while they initiate IM.
ReplyDeleteHello,,,im just thinking if it is possible to divide the codes on connect button. by creating 2 buttons[connect,send].connect is just simply notify you if its connected, then send is to send a message to the server. can anyone help me?
ReplyDeleteI want to know which protocol is being used here. Is it telnet protocol ?
ReplyDeleteAwesome ..works very well..:-)
ReplyDeleteIs it working over 4G connection? each device are not in same local network but have 4G connection. But I cannot send the socket. Pls how to solve it
ReplyDeletehello san,
ReplyDeleteI haven't tried on mobile network. Somebody said the service provider will block the ports. So actually cannot, because of the mobile network service, not by the program.
ThanQ very Much For Best Script
ReplyDeleteIt is Most Use full For Me But I have Some Problem is There any way to Read
Server Mobile Local Ip Address
i dont want enter Manually ip address in client side Mobile
hello The Creator,
ReplyDeleteI have no any good idea for your question.
Anyway, you can scan ip in your network, to find which devices can be reached. Scan Reachable IP to discover devices in network
Dear Sir,
ReplyDeleteYour code work fine,
But I want create once clientThread and reuse it to send different massages to server
because I need to send massage within one millisecond to the server
How can I use this with different network. It works only when both thw server an clients are in same networks.
ReplyDeletehello ranjitha ak,
ReplyDeleteIn my understanding, it depends on network setting, not related to the program.
Thanks for this tutorial, I am usually worried over the fact that people would take time to comment on ur work(post) but you find it very difficult to reply them especially when they need it.
ReplyDeleteHi, Can anybody tell about UDP communication?
ReplyDeleteThis program only partially works for me - pressing connect does show correct messages on the server device, but the client app only receives the input stream the one time into the buffer, then "inputStream.read(buffer)" receives no more data from the server and blocks the thread - i.e. never exits the while loop below.
ReplyDeletewhile ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
Appreciate your time for such a great tutorial...its Awesome, Loved it...simply the best :)
ReplyDeleteHi,
ReplyDeleteIs it possible to do in UDP? I am working on this type of my student project.
Thanks
It is better to close inputstream after read data:
ReplyDelete...
InputStream inputStream = socket.getInputStream();
...
inputStream.close();
Great example I was struggling with it before I found this post.
ReplyDeleteI just can figure out how to send a String to the client?
Do I add the String to the ByteArrayOutputStream?
If you can show me I would appreciate it, Thanks.
Being new to this and would like to learn more. At present want to use android device with graphical buttons to send various commands via telnet?? Or other bidirectional protocol. Any help or links would be appreciated.
ReplyDeletePlease Share more Tutorials
ReplyDeleteVery Interesting Blog Post .Now a Days All the People in the world are Connected together by the Technology. Mainly makes human life Much Easier.
I Liiiike this tutorial
Very good, excellent post!
ReplyDeleteVery informative. Thanks for posting
ReplyDeleteNot working for multiple devices connection.
ReplyDelete