简体   繁体   English

Android TCP通过一个套接字发送数据

[英]Android TCP send data trough one socket

Having the following code: 具有以下代码:

public static PrintWriter outToServer;

private static Socket clientSocket;
    public static void register(InetAddress ip, int port, String name) {
    try {
        Utils.ip = ip;
        Utils.port = port;
        Utils.name = name;

        clientSocket = new Socket(Utils.ip, Utils.port);
        outToServer = new PrintWriter(clientSocket.getOutputStream(),true);

        send("reg:" + name);
}   catch (Exception e) {
        e.printStackTrace();
    }
 }
public static void send(String str) {
        outToServer.println(str);
}

I'm calling the register method once, at the application's start. 在应用程序启动时,我一次调用了register方法。 Ever after I'm using the send method to send data to the server. 在我使用send方法将数据发送到服务器之后。 The problem is that only the first send called from register is properly received from the server. 问题在于只有从register调用的第一个send才从服务器正确接收。 All the others are being sent, but not received(Or if they are, i don't see them being displayed). 其他所有邮件都已发送但未收到(或者,如果没有,我看不到它们被显示)。 My server code: 我的服务器代码:

 public static void main(String argv[]) throws Exception {
  String clientSentence;
 ServerSocket welcomeSocket = new ServerSocket(9876);
 while (true) {
  Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
  new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
     }
  }

Ok, but when i try this code from the client, it works by sending a little bit more traffic(I don't want that). 好的,但是当我从客户端尝试此代码时,它通过发送更多的流量来工作(我不想要这样)。

public static PrintWriter outToServer;

private static Socket clientSocket;
    public static void register(InetAddress ip, int port, String name) {
     try {
      Utils.ip = ip;
      Utils.port = port;
      Utils.name = name;

    send("reg:" + name);
}   catch (Exception e) {
    e.printStackTrace();
}
  }
  public static void send(final String str) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                clientSocket = new Socket(Utils.ip, Utils.port);
                outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
                outToServer.println(str);
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

I need a little explanation on this one. 我需要对此做一些解释。
From one socket can you have multiple OutPutStreams? 从一个套接字可以有多个OutPutStreams?
Why am i getting socketClosed exception when i close an OutPutStream, and try to open a new one on the same socket. 当我关闭OutPutStream并尝试在同一套接字上打开一个新的套接字时,为什么会出现socketClosed异常。 I am defining outToServer only in send now: 我仅在立即send定义outToServer

    public static void send(final String str) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
                outToServer.println(str);
                outToServer.close();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

You need to set TCP_NODELAY on the socket. 您需要在套接字上设置TCP_NODELAY The default is for data to be buffered until it will fill an entire packet. 默认情况下,数据将一直缓存到填充整个数据包为止。 When the buffer is full, a packet is sent. 当缓冲区已满时,将发送一个数据包。 However, for this protocol you want the data to be sent immediately so that the server can respond. 但是,对于此协议,您希望立即发送数据,以便服务器可以响应。

( https://stackoverflow.com/a/33658536/1172714 ) https://stackoverflow.com/a/33658536/1172714

From one socket can you have multiple OutputStreams? 从一个套接字可以有多个OutputStreams?

The socket only has one input stream and one output stream. 该套接字只有一个输入流和一个输出流。

Why am i getting socketClosed exception when i close an OutputStream, and try to open a new one on the same socket. 当我关闭OutputStream并尝试在同一套接字上打开一个新的套接字时,为什么会出现socketClosed异常。

Because closing a socket input or output stream closes the socket, as it says in the Javadoc. 因为关闭套接字输入或输出流会关闭套接字,如Javadoc中所述。

NB The server code you posted never closes anything. 注意:您发布的服务器代码永远不会关闭任何内容。 The client code you posted never closes anything and only sends one message. 您发布的客户端代码永远不会关闭任何内容,只会发送一条消息。

NB 2 PrintWriter swallows exceptions and should not be used over the network. NB 2 PrintWriter会吞下异常,因此不应在网络上使用。 Use BufferedWriter. 使用BufferedWriter。

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

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