两个Android模拟器间Socket通信的问题 10C

代码如下
客户端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
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.TextView;

public class MainActivity extends Activity {

Socket socket = null;
String buffer = "";
TextView txt1;
Button send;
EditText ed1;
String geted1;
public Handler myHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (msg.what == 0x11) {
            Bundle bundle = msg.getData();
            txt1.append("server:" + bundle.getString("msg") + "\n");
        }
    }

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txt1 = (TextView) findViewById(R.id.TextView);
    send = (Button) findViewById(R.id.button);
    ed1 = (EditText) findViewById(R.id.EditText);
    new MyThread("link building").start();
    send.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            geted1 = ed1.getText().toString();
            txt1.append("client:" + geted1 + "\n");
            // 启动线程 向服务器发送和接收信息
            new MyThread(geted1).start();
        }
    });

}

class MyThread extends Thread {

    public String txt1;

    public MyThread(String str) {
        txt1 = str;
    }

    @Override
    public void run() {
        // 定义消息
        Message msg = new Message();
        msg.what = 0x11;
        Bundle bundle = new Bundle();
        bundle.clear();
        try {
            // 连接服务器 并设置连接超时为5秒
            socket = new Socket();
            socket.connect(new InetSocketAddress("10.0.2.2", 5555), 5000);
            // 获取输入输出流
            OutputStream os = socket.getOutputStream();
            BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // 读取发来服务器信息
            String line = null;
            buffer = "";
            while ((line = bff.readLine()) != null) {
                buffer = line + buffer;
            }

            // 向服务器发送信息
            os.write(txt1.getBytes("gbk"));
            os.flush();
            bundle.putString("msg", buffer.toString());
            msg.setData(bundle);
            // 发送消息 修改UI线程中的组件
            myHandler.sendMessage(msg);
            // 关闭各种输入输出流
            bff.close();
            os.close();
            socket.close();
        } catch (SocketTimeoutException aa) {
            // 连接超时 在UI界面显示消息
            bundle.putString("msg", "connect failed");
            msg.setData(bundle);
            // 发送消息 修改UI线程中的组件
            myHandler.sendMessage(msg);
        } catch (IOException e) {
            bundle.putString("msg", "error");
            msg.setData(bundle);
            // 发送消息 修改UI线程中的组件
            myHandler.sendMessage(msg);
            e.printStackTrace();
        }
    }
}

}

服务器:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.os.Vibrator;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

public static ServerSocket serverSocket = null;
public static TextView textview1;



String buffer = "";
public static Handler mHandler = new Handler() {
    @Override
    public void handleMessage(android.os.Message msg) {
        if (msg.what==0x11) {
            Bundle bundle = msg.getData();
            textview1.append("client:"+bundle.getString("msg")+"\n");

        }
    };
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textview1 = (TextView) findViewById(R.id.textview1);


    new Thread() {
        public void run() {
            Bundle bundle = new Bundle();
            bundle.clear();
            OutputStream output;
            String str = "wait Link ";
            try {
                serverSocket = new ServerSocket(5555);

                while(true) {
                    Message msg = new Message();
                    msg.what = 0x11;
                    try {
                        Socket socket = serverSocket.accept();
                        output = socket.getOutputStream();
                        output.write(str.getBytes("UTF-8"));
                        output.flush();
                        socket.shutdownOutput();
                        //mHandler.sendEmptyMessage(0);
                        BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String line = null;
                        buffer = "";
                        while ((line = bff.readLine()) != null) {
                            buffer = line + buffer;
                        }
                        bundle.putString("msg", buffer.toString());
                        msg.setData(bundle);
                        // 发送消息 修改UI线程中的组件
                        mHandler.sendMessage(msg);
                        bff.close();
                        output.close();
                        socket.close();
                    } catch (IOException e) {
                        bundle.putString("msg", "connect failed");
                        msg.setData(bundle);
                        // 发送消息 修改UI线程中的组件
                        mHandler.sendMessage(msg);
                        e.printStackTrace();
                    }
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        };
    }.start();
}

}

问题是Socket链接始终无法建立,请问是什么原因

1个回答

Client:

 public class Client extends Activity
{
    private Socket socket;
    private static final int SERVERPORT = 4000;
    private static final String SERVER_IP = "10.0.2.2";

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        new Thread(new ClientThread()).start();
    }

    public void onClick(View view)
    {
        try
        {
            EditText et = (EditText) findViewById(R.id.EditText01);
            String str = et.getText().toString();

            Log.i("liu", "点击按钮");

            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); // TODO
            out.println(str);
        }
        catch (Exception e)
        {
            Log.i("liu", "write失败");
            e.printStackTrace();
        }
    }

    class ClientThread implements Runnable
    {

        @Override
        public void run()
        {
            try
            {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                socket = new Socket(serverAddr, SERVERPORT);
            }
            catch (UnknownHostException e1)
            {
                e1.printStackTrace();
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }
        }
    }
}

Server:

 public class Server extends Activity
{
    private ServerSocket serverSocket;
    private Handler updateConversationHandler;
    private Thread serverThread = null;
    private TextView text;
    public static final int SERVERPORT = 6000;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        text = (TextView) findViewById(R.id.text2);

        updateConversationHandler = new Handler();

        this.serverThread = new Thread(new ServerThread());
        this.serverThread.start();

    }

    @Override
    protected void onStop()
    {
        super.onStop();
        try
        {
            serverSocket.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private class ServerThread implements Runnable
    {

        public void run()
        {
            Socket socket = null;
            try
            {
                serverSocket = new ServerSocket(SERVERPORT);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            while (!Thread.currentThread().isInterrupted())
            {
                try
                {
                    socket = serverSocket.accept(); // TODO

                    CommunicationThread commThread = new CommunicationThread(socket);
                    new Thread(commThread).start();
                }
                catch (IOException e)
                {
                    Log.i("liu", "socket.accept()失败");

                    e.printStackTrace();
                }
            }
        }
    }

    private class CommunicationThread implements Runnable
    {
        private Socket clientSocket;
        private BufferedReader input;

        public CommunicationThread(Socket clientSocket)
        {
            this.clientSocket = clientSocket;

            Log.i("liu", "获取到了client的Socket");

            try
            {
                this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream())); // TODO
            }
            catch (IOException e)
            {
                Log.i("liu", "input获取失败");
                e.printStackTrace();
            }
        }

        public void run()
        {
            while (!Thread.currentThread().isInterrupted())
            {
                try
                {
                    String read = input.readLine(); // TODO
                    Log.i("liu", read);
                    updateConversationHandler.post(new updateUIThread(read));
                }
                catch (IOException e)
                {
                    Log.i("liu", "input读取失败");
                    e.printStackTrace();
                }
            }
        }
    }

    private class updateUIThread implements Runnable
    {
        private String msg;

        public updateUIThread(String str)
        {
            this.msg = str;
        }

        @Override
        public void run()
        {
            text.setText(text.getText().toString() + "Client Says: " + msg + "\n");
        }

    }

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问