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> &
补充:移动开发 , Android ,