网络通信都要用到套接字socket,用于描述IP地址和端口,是一个通信链的句柄。在Internet上的主机一般运行了多个服务软件,同时提供几种服务。每种服务都打开一个Socket,并绑定到一个端口上,不同的端口对应于不同的服务。Socket和ServerSocket类库位于java .net包中。ServerSocket用于服务器端,Socket是建立网络连接时使用的。在连接成功时,应用程序两端都会产生一个Socket实例,操作这个实例,完成所需的会话。
下面以模拟器作为客户端,以PC为服务器端,进行连接通信和数据交换:
特别需要注意的是,Android模拟器有一个固定的本地IP--10.0.2.2,在用套接字建立通讯时,必须使用这个IP,而不是PC的IP或者是localhost。
首先创建android模拟器客户端:
资源文件
/res/values/string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, Socket_Android!</string>
<string name="app_name">Socket_Android</string>
<string name="TextView01">这里显示接受到服务器发来的信息</string>
<string name="Button01">测试连接</string>
<string name="EditText01">请输入内容</string>
</resources>
布局文件
/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!--
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
-->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/TextView01"
android:id="@+id/TextView01" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/EditText01"
android:id="@+id/EditText01" />
<Button
android:id="@+id/Button01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/Button01" />
<TextView android:id="@+id/tx"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
源代码
package com.liwei;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TestClientActivity extends Activity {
private TextView mTextView = null;
private EditText mEditText = null;
private TextView tx1 = null;
//本地IP
public static final String IP="10.0.2.2";
//与服务端连接的端口
public static final int PORT= 51706;
private Button mbutton = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mbutton = (Button) findViewById(R.id.Button01);
mEditText = (EditText) findViewById(R.id.EditText01);
mTextView = (TextView) findViewById(R.id.TextView01);
tx1 = (TextView) findViewById(R.id.tx);
mbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setTitle("android -- PC");
Socket socket = null;
try{
InetAddress serverAddr = InetAddress.getByName(IP);
socket = new Socket(serverAddr,PORT);
// 将信息通过这个对象来发送给Server
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
//接受服务器信息
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
//得到服务器信息
String msg = in.readLine();
//在页面上进行显示
tx1.setText(msg);
String clientMsg ="";
clientMsg = mEditText.getText().toString();
out.write(clientMsg);
//out.println(msg);
out.flush();
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
}finally{
try{
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
});
}
}
下面是建立在PC上的服务器端源代码:
package res;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable {
public static final String SERVERIP = "10.0.2.2";
public static final int SERVERPORT = 51706;
String str ="";
public void run() {
try {
System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// 等待接受客户端请求
Socket client = serverSocket.accept();
System.out.println("S: Receiving...");
try {
// 接受客户端信息
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
// 发送消息
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(client.getOutputStream())),
true);
// 设置返回信息
out.println("my name is server");
out.flush();
str =str+"\n" + in.readLine();
//通信记录保存在文件中
File file = new File("F:\\DB/file/android.txt");
FileOutputStream fops = new FileOutputStream(file);
byte[] b = str.getBytes();
for (int i = 0; i < b.length - 1; i++) {
fops.write(b[i]);
System.out.println(b.toString());
}
System.out.println("S: Received: '" + str + "'");
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
client.close();
System.out.println("S: Done.");
}
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread desktopServerThread = new Thread(new Server());
desktopServerThread.start();
}
}