import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.*; public class MyServer { public static void main(String[] args) throws Exception{ ServerSocket server=new ServerSocket(1000); Socket clink=server.accept(); PrintStream out=new PrintStream(clink.getOutputStream()); BufferedReader in=new BufferedReader(new InputStreamReader(clink.getInputStream())); StringBuffer bu=new StringBuffer(); bu.append("Andorid: "); bu.append(in.readLine()); out.println(bu); in.close(); out.close(); clink.close(); server.close(); } } Andorid用戶端第一步:main.xml[java] <?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" > <Button android:id="@+id/send" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="串連ServerSocket程式" /> <TextView android:id="@+id/info" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="等待程式的串連" /> </LinearLayout> 第二步:編寫JAVA 類 [java] package com.android.main; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class ActivityMain extends Activity { private Button button; private TextView textView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button=(Button)this.findViewById(R.id.send); textView=(TextView)this.findViewById(R.id.info); button.setOnClickListener(new SendOnclickListener()); } class SendOnclickListener implements OnClickListener { public void onClick(View v) { try{ Socket clink=new Socket("10.10.104.57",1000); PrintStream out=new PrintStream(clink.getOutputStream()); BufferedReader in=new BufferedReader(new InputStreamReader(clink.getInputStream())); out.println("發送資訊給ServerSocket"); ActivityMain.this.textView.setText(in.readLine()); in.close(); out.close(); clink.close(); } catch(Exception e){ } } } } 第三步:添加Internet許可權 [java] <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.main" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" /> <uses-permission android:name="android.permission.INTERNET"/><!-- 添加Internet許可權 --> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".ActivityMain" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>