Android socket communication (I)

Source: Internet
Author: User
Tags sendmsg

Android socket communication (I)

Today we will introduce socket communication in Android and write a small program:Android, as the client, sends data to our PC through socket, and the PC is the server.

Two experiments are completed: We first implement on the simulator and then on the real mobile phone.

1.
Set the environment. Both experiments are completed under ubuntu11.04:
The first experiment is the android simulator as the client, and the second experiment is the real Android mobile phone as the client. Both experimental servers are our PCs, and the server side is implemented using C ++, the client is implemented in Java:
IP configuration of the first experiment:
Host eth0: 192.168.1.2
Port: 9400

IP configuration for the second experiment:
Host lwan0: 192.168.1.100
Port: 9500

Note that the first experiment is the android simulator as the client, so you need to set the eth0 IP address of the host, and the second experiment is the real Android mobile phone as the client, it and the PC (server) in a wireless router LAN, we need to set the lwan IP address of the host. However, because the IP addresses of the host and the real mobile phone are automatically allocated by DHCP, no additional configuration commands are required, you can change it to your own IP address.

The configuration command for the first experiment is simple:
Sudo ifconfig eth0 192.168.1.2


First, we will introduce the first experiment:

Because of the particularity of the simulator, We need to map the simulator port to a port of the host to communicate with the simulator.

1.
Port ing:
There is an ADB executable program under platform-tools in Android SDK, my path is android-sdk-linux_x86/platform-tools/ADB, run the following command for port ing:

CD android-sdk-linux_x86/platform-Tools

./ADB forward TCP: 9400 TCP: 9400

The preceding command maps port 9400 of the simulator to port 9400 of the host.The data sent by the simulator to 192.168.1.2: 9400 is mapped to port 9400 of the host.(The Host IP address is 192.168.1.2), whileOur host only needs to listen to local port 9400.. Here we use TCP
Socket

2.
After the environment is configured and the basic principles are understood, go directly to the code. The following is the client code, which is 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 ();}/** called when the activity is first created. * // @ 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 {/* connect to the server */socket = new socket (server_host_ip, server_host_port);/* Get the output stream */output = 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:orientation="vertical" >    <TextView        android:layout_width="fill_parent"        android:layout_height="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>

Do not forget to add the network access permission in androidmanifest. xml:
<Uses-Permission Android: Name = "android. Permission. Internet"/>

Compile and download the above Code to the simulator.

3.
The server code is 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 1024int 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] = '\0';    printf("Got %d bytes: %s\n", size, buffer);  }  /* close the socket */  close(client_sockfd);        return 0;}


Makefile:

all: server.cgcc -g -Wall -o server server.cclean:rm -rf *.o server

4.
Running result:

First, run the server code, and then run the simulator's bogoclient program. For example, the PC is waiting for the simulator to be connected, and the text dialog box and send button of the simulator are not available before connection:

Click Connect to connect. After the connection is successful, the text box and send button are available. The CONNECT button is unavailable and the host changes from waiting for connection to waiting for data:

Enter some text and press the send button. The PC will print the text data sent from the simulator:


Note: If the connect refused prompt is displayed when the simulator is connected, end the bogoclient of the simulator and the server on the PC, and start again.



The code is not explained much. The comments are quite detailed. For details about TCP communication on PC, refer:

Http://blog.csdn.net/htttw/article/details/7519964



Finally, I upload both the server and client for you to download:

Http://download.csdn.net/detail/htttw/4307606



In the next article, we will transplant this program to a real Android phone:

Http://blog.csdn.net/htttw/article/details/7574409


Done!


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.