PC服务器:
package PCServerSocket;
import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket;
public class PCServerSocket { public static void main(String[] args) throws IOException{ ServerSocket ss=new ServerSocket(1982); while(true){ Socket s=ss.accept(); OutputStream os=s.getOutputStream(); os.write("你好,你收到了服务器的新年祝福!\n".getBytes("utf-8")); os.close(); s.close(); } } } Android 客户端:
package com.example.androidclientsocket;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.net.UnknownHostException;
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener{ private EditText show; private String line; private Button button; public static final int UPDATE_TEXT=1; private Handler handler=new Handler(){ public void handleMessage(Message msg){ switch(msg.what){ case UPDATE_TEXT: show.setText("来自服务器的数据:"+line); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_layout); show=(EditText) findViewById(R.id.edit); button=(Button) findViewById(R.id.button); button.setOnClickListener(this); } @Override public void onClick(View v){ switch(v.getId()){ case R.id.button: new Thread(new Runnable(){ @Override public void run(){ try { Socket socket=new Socket("10.2.110.145",1982); socket.setSoTimeout(10000); BufferedReader br=new BufferedReader(new InputStreamReader( socket.getInputStream())); line=br.readLine(); //show.setText("来自服务器的数据:"+line); Message message=new Message(); message.what=UPDATE_TEXT; handler.sendMessage(message); Log.i("Lzy","read data:"+line); br.close(); socket.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); break; default: break; } } } 注意:1、socket链接服务器应在子程序中
2、在模拟器中运行没为题如果在,真机中测试应关闭杀毒软件,防火墙,并注意wifi网络。(我的笔记本,与手机在统一wifi网络中可正常运行)
3.在子线程中不可以改变控件,需要异步处理消息机制
4、androidManifest.xml中要添加权限<uses-permission android:name="android.permission.INTERNET"/>