Android Socket Communications (upper)
Today we introduce the socket communication under Android and write a small program: Android as the client, Through the socket to send data to our PC, PC is the server. The
is done in two experiments: we first implement it on the simulator and then implement it on the real phone.
1.
Setting the environment, two experiments are done under ubuntu11.04:
The first experiment is the Android simulator as the client, the second experiment is the real Android phone as the client, the two experimental servers are our PCs, and the server end is implemented in C + +, The client is implemented in Java:
The IP configuration of the first experiment:
host eth0:192.168.1.2
PC server port: 9400
IP configuration for the second experiment:
Host lwan0:192.168.1.100
PC server port: 9500
Note that the first experiment was the Android emulator as the client, so to set the IP address of the host's eth0, And the second experiment is the real Android phone as the client, it and PC (server) in a wireless router LAN, so we want to set the host's Lwan IP address, but because the host and the real phone IP is the router DHCP automatically allocated, so no additional configuration commands, You can change to your own IP address.
The configuration command for the first experiment is simple:
sudo ifconfig eth0 192.168.1.2
first describes the first experiment:
because The particularity of the simulator, we need to map the port of the simulator to a port on the host, so that we can communicate with the simulator.
1.
Port mappings:
There is a adb executable under the platform-tools of the Android SDK, my path is android-sdk-linux_ X86/PLATFORM-TOOLS/ADB, run the following command for port mapping:
CD Android-sdk-linux_x86/platform-tools
./adb forward tcp:9400 tcp:9400
The above command means to map the emulator's 9400 port to the host's 9400 port, so that the data that the emulator sends to the 192.168.1.2:9400 is mapped to the host's 9400 Port (the host's IP address is 192.168.1.2), and Our host can only listen to the local 9400 port . Here we use the TCP socket
2.
Environment configuration complete and understand the basic principles, directly on the code, the following is the client code, implemented in Java:
Src/bogoclientactivity.java
Package bogo.client.com;
Import java.io.IOException;
Import Java.io.PrintStream;
Import Java.net.Socket;
Import java.net.UnknownHostException;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.Toast;
public class Bogoclientactivity extends activity {/* server address/private final String server_host_ip = "192.168.1.2";
/* Server Port * * Private final int server_host_port = 9400;
Private Button Btnconnect;
Private Button btnsend;
Private EditText editsend;
private socket socket;
Private PrintStream output;
public void Toasttext (String message) {Toast.maketext (this, message, Toast.length_long). Show ();
public void HandleException (Exception e, String prefix) {e.printstacktrace ();
Toasttext (prefix + e.tostring ()); The/** called when the ' activity is ' is a. */@Override public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Initview ();
Btnconnect.setonclicklistener (New Button.onclicklistener () {@Override public void OnClick (View v) {
Initclientsocket ();
}
});
Btnsend.setonclicklistener (New Button.onclicklistener () {@Override public void OnClick (View v) {
SendMessage (Editsend.gettext (). toString ());
}
});
public void Initview () {btnconnect = (Button) Findviewbyid (r.id.btnconnect);
Btnsend = (Button) Findviewbyid (r.id.btnsend);
Editsend = (edittext) Findviewbyid (r.id.sendmsg);
Btnsend.setenabled (FALSE);
Editsend.setenabled (FALSE);
public void Closesocket () {try {output.close ();
Socket.close ();
catch (IOException e) {handleexception (E, "close exception:"); } private void Initclientsocket () {try {/* Connection server/socket = new SOCKet (Server_host_ip, server_host_port);
/* Get output stream = new PrintStream (Socket.getoutputstream (), True, "utf-8");
Btnconnect.setenabled (FALSE);
Editsend.setenabled (TRUE);
Btnsend.setenabled (TRUE);
catch (Unknownhostexception e) {handleexception (E, "Unknown host exception:" + e.tostring ());
catch (IOException e) {handleexception (E, "IO exception:" + e.tostring ());
} private void SendMessage (String msg) {output.print (msg); }
}
Layout/main.xml
<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
android:layout_width=" fill_parent "
android:layout_height=" fill_parent "
android:o" rientation= "vertical" >
<textview
android:layout_width= "Fill_parent"
Wrap_content "
android:text=" @string/hello "/>
<button
android:id=" @+id/btnconnect " Android:layout_width= "Fill_parent"
android:layout_height= "wrap_content"
android:text= "@string Connect "/>
<edittext
android:id=" @+id/sendmsg
android:layout_width= "Match_parent
" android:layout_height= "Wrap_content"
android:inputtype= "text"/>
<button android:id=
"@+id/ Btnsend "
android:layout_width=" fill_parent "
android:layout_height=" wrap_content "
android:text=" @string/send "/>
</LinearLayout>
Don't forget to add access to network permissions in Androidmanifest.xml:
<uses-permission android:name= "Android.permission.INTERNET"/>
compile and download the above code into the emulator
3.
Server-side code, implemented in C + +:
server.c
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h>
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #define PORT 9400 #define Max_buffer 1024
int main () {/* Create a socket/int SERVER_SOCKFD = socket (af_inet, sock_stream, 0);
struct sockaddr_in server_addr;
server_addr.sin_family = af_inet;
SERVER_ADDR.SIN_ADDR.S_ADDR = inet_addr ("192.168.1.2");
Server_addr.sin_port = htons (port);
/* Bind with the local file */bind (SERVER_SOCKFD, (struct sockaddr *) &server_addr, sizeof (SERVER_ADDR));
/* Listen * * Listen (SERVER_SOCKFD, 5);
int size;
Char Buffer[max_buffer + 1];
int CLIENT_SOCKFD;
struct sockaddr_in client_addr;
socklen_t len = sizeof (CLIENT_ADDR);
/* Accept a connection * * printf ("Waiting connection...\n");
CLIENT_SOCKFD = Accept (SERVER_SOCKFD, (struct sockaddr *) &client_addr, &len);
printf ("Connection established!\n");
while (1) {printf ("Waiting message...\n");
/* Exchange Data */size = read (CLIENT_SOCKFD, buffer, max_buffer);
Buffer[size] = ' the ';
printf ("Got%d bytes:%s\n", size, buffer);
}/* Close the socket */close (CLIENT_SOCKFD);
return 0; }
Makefile:
ALL:SERVER.C
gcc-g-wall-o server server.c clean
:
rm-rf *.O Server
4.
Run Result:
Run the server code first, then run the emulator's Bogoclient program, the following figure, the PC is waiting for the emulator to connect, and the Emulator Text dialog box and send button are not available before the connection is made:
Click Connect button to connect, after the successful connection we found that the text box and send button is available, the Connect button is unavailable, and the host from the waiting connection status into waiting data status:
When you enter some text and press the Send button, the PC prints out the text data from the simulator:
Note that if the emulator is connected to the connect refused, then the bogoclient of the simulator and the server on the PC are ended, and then started again.
Code but more explanation, the annotation quite detailed, regarding the PC computer TCP communication, may refer to:
http://blog.csdn.net/htttw/article/details/7519964
Finally, I put this server and client two programs are uploaded up for everyone to download:
http://download.csdn.net/detail/htttw/4307606
In the next installment, we're going to transplant this program to a real Android phone:
http://blog.csdn.net/htttw/article/details/7574409
completed.