简体   繁体   English

通过套接字在同一活动中发送和接收数据

[英]sending and recieving data through sockets in the same activity

i'm using TCP socket to send and receive data from the same socket in the same activity through client server thread, the purpose of that is to send a string to other device and that string will trigger a notification once the other device receives it then that device will replay with something like dismiss or accepted, the problem that i'm having is after sending the string the other device receives it and send the dismiss or accepted String but my divice doesn't receive that string i guess there is a problem in my ServerThread be aware that the server thread and client thread are in the same activity used as an inner classes and get called in a button. 我正在使用TCP套接字通过客户端服务器线程在同一活动中从同一套接字发送和接收数据,其目的是向其他设备发送字符串,并且一旦其他设备收到该字符串,该字符串将触发通知,然后该设备将以诸如dismiss或accepted之类的方式重放,我遇到的问题是在发送字符串后,另一台设备收到了该字符串并发送dismiss或accepted字符串,但是我的设备未收到该字符串,我想这是一个问题在我的ServerThread中,请注意,服务器线程和客户端线程处于与内部类相同的活动中,并在按钮中被调用。 code: 码:

ClientThread ClientThread

private class ChatClientThread extends Thread {








          @Override
          public void run() {
           Socket socket = null;
           DataOutputStream dataOutputStream = null;




           try {

            socket = new Socket("192.168.0.113", 23);
            dataOutputStream = new DataOutputStream(
              socket.getOutputStream());



            dataOutputStream.writeUTF("  "+"SolveProblemOrder_2");
            dataOutputStream.flush();

            ServerThread serv =new ServerThread();
            serv.start();

           } catch (UnknownHostException e) {
            e.printStackTrace();
            final String eString = e.toString();
            TicketDetails.this.runOnUiThread(new Runnable() {

             @Override
             public void run() {
              Toast.makeText(TicketDetails.this, eString, Toast.LENGTH_LONG).show();
             }

            });
           } catch (IOException e) {
            e.printStackTrace();
            final String eString = e.toString();
            TicketDetails.this.runOnUiThread(new Runnable() {

             @Override
             public void run() {
              Toast.makeText(TicketDetails.this, eString, Toast.LENGTH_LONG).show();
             }

            });
           } finally {
            if (socket != null) {
             try {
              socket.close();
             } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
            }

            if (dataOutputStream != null) {
             try {
              dataOutputStream.close();
             } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
            }



            TicketDetails.this.runOnUiThread(new Runnable() {

             @Override
             public void run() {

             }

            });
           }

          }


         }

ServerThread ServerThread

public class ServerThread extends Thread {

          private ServerSocket serverSocket;
          private Socket clientSocket;


          public void run(){

            try{
              // Open a server socket listening on port 23
              InetAddress addr = InetAddress.getByName(getLocalIpAddress());
              serverSocket = new ServerSocket(23, 0,addr);
              try{
              clientSocket = serverSocket.accept();
             DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
             String newMsg = null;
             Toast.makeText(getApplicationContext(), newMsg, Toast.LENGTH_LONG).show();
              // Client established connection.
              // Create input and output streams
              while (true) {
                     if (dataInputStream.available() > 0) {
                      newMsg = dataInputStream.readUTF();
                              }

              }}catch(Exception e){
                     e.printStackTrace();
                 }
              // Perform cleanup



            } catch(Exception e) {
              // Omitting exception handling for clarity
            }
          }

          private String getLocalIpAddress() throws Exception {
            String resultIpv6 = "";
            String resultIpv4 = "";

              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()){
                      if (inetAddress instanceof Inet4Address) {
                        resultIpv4 = inetAddress.getHostAddress().toString();
                        } else if (inetAddress instanceof Inet6Address) {
                          resultIpv6 = inetAddress.getHostAddress().toString();
                        }
                    }
                }
            }
            return ((resultIpv4.length() > 0) ? resultIpv4 : resultIpv6);
          }
        }

i start those two threads in a button Click listener: 我在一个按钮单击侦听器中启动了这两个线程:

ChatClientThread chatClient=new ChatClientThread();
                        chatClient.start();
ServerThread serv =new ServerThread();
        serv.start();

if this won't work using server/client in the same activity using the same port is there any other way to listen to a socket like is there a built in listener or something like that. 如果在使用相同端口的同一活动中使用服务器/客户端无法正常工作,是否还有其他方法可以监听套接字,例如是否有内置监听器或类似的东西? any help is appreciated 任何帮助表示赞赏

You write to socket thru socket.getOutputStream() and you must read from InputStream of socket.getInputStream() ; 您通过socket.getOutputStream()写入套接字,并且必须从socket.getInputStream()的InputStream读取; You can adapt your code . 您可以修改代码。 Your server use InputStream from socket to read data ,so you must to do also in your client code , cause you want also to receive data not only to send. 您的服务器使用套接字上的InputStream读取数据,因此您必须在客户端代码中也这样做,因为您还希望不仅接收数据也要发送数据。

check this out just read is is very simple. 检查一下,只是读是很简单的。

https://systembash.com/a-simple-java-tcp-server-and-tcp-client/ https://systembash.com/a-simple-java-tcp-server-and-tcp-client/

See the code for reading from socket taht start with : 请参阅从套接字开始读取的代码:

BufferedReader inFromClient =
               new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

and code for writing to socket: 和用于写入套接字的代码:

   DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

or search google : java client server . 或搜索google:java客户端服务器。

The ideea is that you send data to the socket outputstream and you can read it from same socket inputstream. 想法是将数据发送到套接字输出流,并且可以从同一套接字输入流读取数据。

you see here example it read data from socket input and send data thru socket output , to server 您在此处看到的示例从套接字输入读取数据,并通过套接字输出将数据发送到服务器

String sentence;
  String modifiedSentence;
  BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
  Socket clientSocket = new Socket("localhost", 6789);
  DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  sentence = inFromUser.readLine();
  outToServer.writeBytes(sentence + '\n');
  modifiedSentence = inFromServer.readLine();
  System.out.println("FROM SERVER: " + modifiedSentence);
  clientSocket.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM