如何通过Java中的Socket接收纯文本

时间:2013-12-23 05:58:41

标签: java sockets

我试图通过Socket发送纯文本。所以我在StackOverflow中发现了一个帖子,我跟着它,我猜它是我写的但是,我怎么能在客户端接受那个纯文本作为字符串呢? 我使用了BufferedReader()InputStreamReader()类,但是抛出了异常。

Exception : exception java.net.SocketException: Broken pipe

这是代码:
服务器:

OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
osw.write(fileName, 0, fileName.length());

客户端:

InputStream in = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String fileName = br.readLine();
br.close();

一些帮助会很棒。 :)谢谢。

客户端代码:

public void soc_client() throws Exception {
    long time = System.currentTimeMillis();
    long totalRecieved = 0;

    try {
        Socket sock = new Socket("172.16.27.106", 55000);
        System.out.println("Hello Client");
        InputStream in = sock.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String fileName = br.readLine();
        File outputFile = new File(fileName + "");
        br.close(); // CLOSING BufferedReader

        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);

        byte[] buffer = new byte[100 * 1024];
        int bytesRead = 0;

        while ((bytesRead = in.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, bytesRead);
            totalRecieved += bytesRead;
            System.out.println("Recieved " + (totalRecieved / 1024)
                    + " kilobytes in "
                    + ((System.currentTimeMillis() - time) / 1000)
                    + " seconds");
        }
        fileOutputStream.close();
        sock.close();
    } catch (Exception e) {
        System.out.println("Exception " + e);
    } finally {
        System.out.println("Recieved " + totalRecieved + " bytes in "
                + (System.currentTimeMillis() - time) + "ms.");
    }
}

2 个答案:

答案 0 :(得分:1)

你正在阅读一条线但是你没有发送一条线,而你也没有关闭OutputWriter。所以readLine()将永远阻止等待行终结者或永远不会来的EOS。

  1. 在邮件中添加换行符。
  2. 关闭OutputWriter.

答案 1 :(得分:-1)

使用套接字以客户端服务器的方式发送和传输文本,我发布了一个简单的基本代码,在运行时向客户端发送HELLO WORLD响应。

//服务器端

ServerSocket server= new ServerSocket(1166); // //1166 -port no. u can use any other too.
Socket  s= server.accept(); // makes a connection whenever a client requests.

OutputStream os= socket.getOutputStream();

DataOutputStream dos = new DataOutputStream(os);

dos.writeUTF("Hello World");

dos.close();

//客户端

Socket socket= new Socket("Ip address of you server" , 1166) ;
InputStream is= new InputStream();
DataInputStream dis = new DataInputStream(is);

String msg=dis.readUTF();
System.out.println(msg);
dis.close();

现在,在服务器计算机上运行一次代码后,再运行客户端代码,服务器现在将使用Hello World回复您。