0

我正在尝试使用 java 程序读取数据并将其写入服务器。我正在使用控制台写入数据。我可以成功地将数据写入服务器,但是当我尝试读取服务器发送的数据时,问题就来了。

import java.io.*;
import java.net.*;


public class EMSSocketConnection {



    public static void main(String[] args) throws Exception {

        createSocket();
    }

    private static void sendMessage(DataOutputStream out) throws Exception
    {
        try 
        {

            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String userOutput;
            while ((userOutput = stdIn.readLine()) != null)
            {
                out.writeBytes(userOutput);
                out.write('\n');
            }
            out.flush();

        }
        catch(Exception ex)
        {
            System.out.println(ex.getStackTrace());

        }
        finally
        {
            out.close();
        }
    }


    private static void readResponse(DataInputStream in) throws Exception
    {
        try
        {
            byte[] data = new byte[1024];
            in.readFully(data);
            System.out.println(data);


        }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage());

        }
        finally
        {
            in.close();
        }
    }

    private static void createSocket()
    {

        try
        {
            int port = 2345;
            InetAddress address = InetAddress.getByName("192.100.100.129");
            final Socket client = new Socket(address, port);
            final DataOutputStream out = new DataOutputStream(client.getOutputStream());
            final DataInputStream in = new DataInputStream(client.getInputStream());

            System.out.println("Successfully Connected");



            new Thread() {
                public void run() {
                    synchronized(client)
                    {
                        try {
                            while(true)
                            {
                            sendMessage(out);
                            readResponse(in);
                            }
                        }
                        catch (Exception ex)
                        {
                            System.out.println(ex.getMessage());
                        }
                    }
                }
            }.start();
        }
        catch(Exception ex)
        {
            ex.getStackTrace();
        }
    }

}

谁能告诉我如何成功地从服务器读取数据?

4

1 回答 1

2

您的服务器是否将 1024 字节写入其输出?如果没有,你的代码

byte[] data = new byte[1024];
in.readFully(data);

将无限期地阻塞和等待。

一个更好的习惯用法是这样做:

byte [] data = new byte[in.available()];
in.readFully(data);

您不能随便从流中读取数据并假设您将获得预期的数据。流受到 IO 延迟和缓冲的影响,您需要注意这一点,尤其是在处理网络 IO 时。

于 2012-04-04T10:16:19.573 回答