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>
不要忘了,在AndroidManifest.xml中添加访问网络权限:
<uses-permission android:name="android.permission.INTERNET" />
把上面的代码编译并下载到手机中
3.
服务器端的代码,用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 9500
- #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.100");
- 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.c
- gcc -g -Wall -o server server.c
- clean:
- rm -rf *.o server
4.
运行结果:
代码不过多解释了,注释挺详细的,有关pc机上的tcp通信,可以参考:
http://www.linuxidc.com/Linux/2012-06/61802htm
最后,我把这个服务器和客户端两个程序都上传上来,供大家下载:
免费下载地址在 http://linux.linuxidc.com/
用户名与密码都是www.linuxidc.com
具体下载目录在 /2012年资料/6月/2日/Android Socket通信(下)/
