【问题标题】:How to send data from ServerSocket to Socket?如何将数据从 ServerSocket 发送到 Socket?
【发布时间】:2011-05-22 21:46:12
【问题描述】:

在问了这么多关于 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() 方法。*我使用了客户端套接字...

【问题讨论】:

  • 你的 Threadsendmsg 类是做什么的?是客户端吗?
  • 它将味精发送到服务器。我尝试了同样的服务器套接字类将味精发送到客户端,但它没有工作......
  • 请把客户端代码也放上来,我找了很多,但Invain,我花了整整一个星期,但仍然无法实现。
  • ServerSockets 无法发送或接收数据。这个问题毫无意义。
  • @EJP - 这个问题并非毫无意义,它只是由于误解了 ServerSocketserver-side 套接字之间的区别导致从接受连接。提供解释比结束问题更有成效。

标签: android multithreading sockets


【解决方案1】:

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

client.getOutputStream();

【讨论】:

    猜你喜欢
    • 2015-09-27
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多