如何将从服务器收到的结果存储到文本文件中

时间:2016-10-31 18:50:21

标签: java sockets

有人可以帮我解决这个问题。我是一个新手,我正在开发一个网络应用程序,我必须创建一个套接字连接到他们已经给我的IP地址和端口,然后将XML消息发送到套接字,最后包含ReadMe.txt文件,我将在那里保存我从服务器收到的内容。这是我的代码

private static Socket socket;

public static void main(String args[])
{
    try
    {
        socket = new Socket( "196.37.22.179", 9011);

        //Send the message to the server
        //PrintStream outstrm = null;
        OutputStream os = socket.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);

        String str;
        str = "<request>";
        str += "<EventType>Authentication</EventType>";
        str += "<event>";
        str += "<UserPin>12345</UserPin>";
        str += "<DeviceId>12345</DeviceId>";
        str += "<DeviceSer>ABCDE</DeviceSer>";
        str += "<DeviceVer>ABCDE</DeviceVer>";
        str += "<TransType>Users</TransType>";
        str += "</event></request>";
        bw.write(str);
        bw.flush();
        System.out.println("Message sent to the server......! ");

        //Get the return message from the server
        InputStream is = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);        
    }
    catch (Exception exception)
    {
        exception.printStackTrace();
    }
    finally
    {
        //Closing the socket
        try
        {
            socket.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您可以使用此代码将文件中的服务器结果存储在

//Get the return message from the server
InputStream is = socket.getInputStream();
OutputStream outputStream = new FileOutputStream(new File("ReadMe.txt"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
    outputStream.write(bytes, 0, read);
}