如何将数据从ServerSocket发送到Socket?

时间:2011-05-22 21:46:12

标签: android multithreading sockets

在询问了很多关于android套接字编程的问题并从stackoverflow的成员那里得到有价值的答案后,我可以做一个很好的工作程序,使用套接字通过wifi连接两个设备。 谢谢大家。 但我仍然有一些问题..

我已经完成了该计划    **数据可以从客户端发送并在serverSocket **处接收 但我仍然没有得到如何从服务器发送可以在客户端接收的数据

服务器套接字代码

private OnClickListener bt_sendListner = new OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub

        String msg=et_msg.getText().toString();
        Log.d("Msg", msg);
        Thread threadsendmsg = new Thread(new Threadsendmsg(msg));
        threadsendmsg.start();

    }
};



public class Threadsendmsg implements Runnable{

    String msg;

    public Threadsendmsg(String msg) {
        // TODO Auto-generated constructor stub
      this.msg=msg;


    }

    public void run() {
        // TODO Auto-generated method stub
         try {

             Looper.prepare();
                Log.d("Msg", "Inside the thread");


             //connected = true; 
                while (true) {
                    try {

                        Log.d("Msg", "Msg to be sent");

                        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(serverSocket.accept().getOutputStream())), true);
                            // where you issue the commands
                            out.println("Client: "+msg);
                            Log.d("Msg", "Msg sent"+out.toString());

                            break;
                    } catch (final Exception e) {
                        handler.post(new Runnable() {

                            public void run() {
                                // TODO Auto-generated method stub
                    tv_chatbox.setText("S: Error= "+ e.getMessage());
                             Log.d("Msg", e.getMessage());   
                            }
                        });
                    }
                }
              //  socket.close();
              //  console.append("\nC: Closed.");
            } catch (final Exception e) {
                handler.post(new Runnable() {

                    public void run() {

                        // TODO Auto-generated method stub
                        tv_chatbox.setText("S: Error= "+ e.getMessage());
                                 Log.d("Msg", e.getMessage());


                        // TODO Auto-generated method stub
                //      console.append("\nC: Error= "+ e.getMessage());

                    }
                });

           //   connected = false;
            }



    }




}



public class ServerThread implements Runnable {

    public void run() { 
        try {
            Looper.prepare();
            if (SERVERIP != null) {
                handler.post(new Runnable() {
                    public void run() {
                        serverStatus.setText("Listening on IP: " + SERVERIP);
                    }
                });
                serverSocket = new ServerSocket(SERVERPORT);
                handler.post(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), serverSocket.getLocalSocketAddress().toString()
                                , Toast.LENGTH_LONG).show();
                                serverStatus.append("\n"+serverSocket.getLocalSocketAddress().toString());

                    }
                });



                Toast.makeText(getApplicationContext(), serverSocket.getLocalSocketAddress().toString()
                , Toast.LENGTH_LONG).show();
                serverStatus.append("\n"+serverSocket.getLocalSocketAddress().toString());
                while (true) {
                    // listen for incoming clients
                    Socket client = serverSocket.accept();
                    handler.post(new Runnable() {
                        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);

                          final  String myline=new String(line);
                            handler.post(new Runnable() {
                                public void run() {
                                    tv_chatbox.setText("Client said:="+myline);

                                    // do whatever you want to the front end
                                    // this is where you can be creative
                                }
                            });
                        }
                        break;
                    } catch (Exception e) {
                        handler.post(new Runnable() {
                            public void run() {
                                serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
                            }
                        });
                        e.printStackTrace();
                    }
                }
            } else {
                handler.post(new Runnable() {
                    public void run() {
                        serverStatus.setText("Couldn't detect internet connection.");
                    }
                });
            }
        } catch (final Exception e) {
            handler.post(new Runnable() {
                public void run() {
                    serverStatus.setText("Error"+e.getMessage());

                }
            });
            e.printStackTrace();
        }
    }
}

* ServerSocket类中没有ServerSocket.getOutputStream()方法。 *我使用过客户端套接字......

1 个答案:

答案 0 :(得分:2)

客户端和服务器都使用相同的类Socket。但客户端手动创建其套接字实例并连接到服务器。另一方面,服务器在某个端口侦听,当客户端连接时,将创建socket for server并从方法accept()返回。 在您的代码中,您可以使用

client.getOutputStream();