读取和写入套接字

时间:2011-12-11 14:33:02

标签: java sockets buffer port

我想要制作一个应用程序(两个应用程序用于移动设备(服务器)和一个用于平板电脑(客户端)),这将允许两个Android设备(一个移动设备和一个平板电脑)之间发送和接收消息。我已设法让两个设备连接但我无法弄清楚如何实际发送消息,然后在另一台设备上显示它。

请帮助:)

移动端(服务器)

public class TabSMSMobileSideActivity extends Activity {

    // default ip
    public static String SERVERIP = "10.0.2.15";
    // designate a port
    public static final int SERVERPORT = 8080;
    private Thread fst;
    private TextView serverStatus;
    private Handler handler = new Handler();
    private ServerSocket serverSocket;
    private Button btnStartServer;
    private TextView txtMessage;

    // instruction protocol
    String messageIn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.server);
        serverStatus = (TextView) findViewById(R.id.server_status);
        txtMessage = (TextView) findViewById(R.id.txtRecieved);
        btnStartServer = (Button) findViewById(R.id.btnStartServer);
        btnStartServer.setOnClickListener(btnStartServerOnClick);
    }

    private OnClickListener btnStartServerOnClick = new OnClickListener() {
        public void onClick(View v) {
            SERVERIP = getLocalIpAddress();
            fst = new Thread(new ServerThread());
            fst.start();
        }
    };

    void read(TextView target) {
        while (1 > 0) {
            try {
                serverSocket = new ServerSocket(SERVERPORT);
                Socket client = serverSocket.accept();
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        client.getInputStream()));
                target.setText(in.readLine());
            } catch (IOException e1) {

            }
        }
    }

    public class ServerThread implements Runnable {

        public void run() {
            try {
                if (SERVERIP != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            serverStatus
                                    .setText("Listening on IP: " + SERVERIP);
                        }
                    });
                    serverSocket = new ServerSocket(SERVERPORT);
                    while (true) {
                        // listen for incoming clients
                        Socket client = serverSocket.accept();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                serverStatus.setText("Connected.");
                            }
                        });

                        try {
                            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                            client.getInputStream()));
                            String line = null;
                            while ((line = in.readLine()) != null) {
                                Log.d("ServerActivity", line);

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        // run all in and out messages through
                                        // here
                                        read(txtMessage);

                                    }
                                });
                            }
                            break;
                        } catch (Exception e) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    serverStatus
                                            .setText("Oops. Connection interrupted. Please reconnect your phones.");
                                }
                            });
                            e.printStackTrace();
                        }
                    }
                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            serverStatus
                                    .setText("Couldn't detect internet connection.");
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus.setText("Error");
                    }
                });
                e.printStackTrace();
            }
        }
    }

    // gets the ip address of your phone's network
    private String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("ServerActivity", ex.toString());
        }
        return null;
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            // make sure you close the socket upon exiting
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

客户

public class TabSMSActivity extends Activity {

    private EditText serverIp;
    private Button connectPhones;
    private EditText txtSendMessage;
    private String serverIpAddress = "";
    private boolean connected = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inbox);

        serverIp = (EditText) findViewById(R.id.server_ip);
        txtSendMessage = (EditText) findViewById(R.id.txtSendMessage);
        connectPhones = (Button) findViewById(R.id.connect_phones);
        connectPhones.setOnClickListener(connectListener);
    }

    private OnClickListener connectListener = new OnClickListener() {

        public void onClick(View v) {
            if (!connected) {
                serverIpAddress = serverIp.getText().toString();
                if (!serverIpAddress.equals("")) {
                    Thread cThread = new Thread(new ClientThread());
                    cThread.start();
                }
            }
        }
    };

    public class ClientThread implements Runnable {

        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                Log.d("ClientActivity", "C: Connecting...");
                Socket socket = new Socket(serverAddr, 8080);
                connected = true;
                while (connected) {
                    try {
                        Log.d("ClientActivity", "C: Sending command.");
                        PrintWriter out = new PrintWriter(
                                new BufferedWriter(new OutputStreamWriter(
                                        socket.getOutputStream())), true);
                        // where you issue the commands
                        out.println("Hey Server!");
                        txtSendMessage.setText("Hey Server");
                        Log.d("ClientActivity", "C: Sent.");
                    } catch (Exception e) {
                        Log.e("ClientActivity", "S: Error", e);
                    }
                }
                socket.close();
                Log.d("ClientActivity", "C: Closed.");
            } catch (Exception e) {
                Log.e("ClientActivity", "C: Error", e);
                connected = false;
            }
        }
    }
}

0 个答案:

没有答案