服务器端:
import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class SimpleServer { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(30000); while(true){ Socket s = ss.accept(); s.close(); } } }
客户端:
package com.example.simpleclient; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Socket; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.TextView; public class MainActivity extends Activity { private TextView tv; private Handler handler ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.textView); handler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub if(msg.what==0x123){ tv.setText("连接成功"); } } }; Thread thread = new Thread(new MyThread(handler)); thread.start(); } } class MyThread implements Runnable{ private Handler handler; public MyThread(Handler handler){ this.handler = handler; } public void run(){ try { Socket socket = new Socket("192.168.23.1",30000); handler.sendEmptyMessage(0x123); } catch (Exception e) { e.printStackTrace(); } } }
手机和电脑连的是同一个网,服务器和客户端一直无法连接成功,不知道是为什么。
解决方案