android socket通訊(下)
在android socket通訊(上),我們完成了一個模擬器上啟動並執行android socket通訊執行個體程式:
http://blog.csdn.net/htttw/article/details/7574372
今天我們將它移植到真實的android手機上,不過要先確保環境配置正確,請參考上一講。
主機的lwan0的ip地址是路由器自動分配的:192.168.1.100,android手機的ip地址是路由器自動分配的:192.168.1.101,可以在主機上ping手機,理論上是通的,不過很奇怪,我經常會碰到ping不通的情況,然後我在android手機裡裝了一個類比終端,ping主機,一般都是通的,難道是android手機的問題?
下面直接上代碼,和上一講的代碼基本沒有差別,改動的部分如下:
1.
ip地址修改過了
2.
連接埠由9400改為了9500(呵呵,這是任意的,不改也可以的)
2.
src/RealclientActivity.java
package real.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 RealclientActivity extends Activity{ /* 伺服器位址 */ private final String SERVER_HOST_IP = "192.168.1.100"; /* 伺服器連接埠 */ private final int SERVER_HOST_PORT = 9500; 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 { /* 串連伺服器 */ socket = new Socket(SERVER_HOST_IP, SERVER_HOST_PORT); /* 擷取輸出資料流 */ 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>
不要忘了,在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 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.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.cgcc -g -Wall -o server server.cclean:rm -rf *.o server
4.
運行結果:
代碼不過多解釋了,注釋挺詳細的,有關pc機上的tcp通訊,可以參考:
http://blog.csdn.net/htttw/article/details/7519964
最後,我把這個伺服器和用戶端兩個程式都上傳上來,供大家下載:
http://download.csdn.net/detail/htttw/4307666