要注意的问题:
- IP是10.0.2.2,而不是localhost或者127.0.0.1。因为localhost或者127.0.0.1是模拟器自己。
- 注意你是否在AndroidManifest.xml里添加了permission:<uses-permission android:name=”android.permission.INTERNET” />
- 不能在主线程里建立socket连接,建议创建一个新的线程。(本人的解决方法,欢迎讨论)
import java.io.*;
import java.net.*;
import java.util.Date;
public class Server {
public static int PORT = 6688;
public void run(){
ServerSocket listener;
try{
listener = new ServerSocket(PORT);
while(true){
System.out.println("The server is running ...");
Socket s = listener.accept();
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
service(is,os);
s.close();
System.out.println("The server is close.");
}
} catch(Exception e){
System.out.println(e);
}
}
public void service(InputStream is,OutputStream os) throws IOException, UnknownHostException{
DataInputStream ins = new DataInputStream(is);
DataOutputStream ous = new DataOutputStream(os);
String input = ins.readUTF();
System.out.println(input);
ous.writeUTF("The message is received");
}
public static void main(String[] args){
Server s = new Server();
s.run();
}
}
客户端
import java.io.*;
import java.net.*;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText et1,et2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=((EditText)findViewById(R.id.editText1));
et2=((EditText)findViewById(R.id.editText2));
((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
(new Thread(new Runnable() {
public void run() {
client();
}
})).start();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void client(){
try{
Socket s = new Socket("10.0.2.2",6688);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
dos.writeUTF("Hello from client.");
String input = dis.readUTF();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), input, Toast.LENGTH_LONG).show();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
}