简体   繁体   English

接收流后关闭套接字连接-Java

[英]Close socket connection after receiving stream - java

I made a tcp server which takes a file name from the client and read the content of the file located on the server and then stream it back to the client. 我制作了一个tcp服务器,该服务器从客户端获取文件名,并读取服务器上文件的内容,然后将其流回客户端。

I also made a client to receive the file. 我还让客户端来接收文件。 My problem is after receiving the file on the client, how do i terminate the loop, so i can close the connection? 我的问题是在客户端上收到文件后,如何终止循环,以便可以关闭连接?

Here is the server code: 这是服务器代码:

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

public class WebTCPServer_file {
    public static void main(String argv[]) throws Exception{
        String request;
        ServerSocket welcomeSocket = new ServerSocket(6790); //opening socket
        while(true){
            Socket connectionSocket = welcomeSocket.accept();
            Scanner inFromClient = new Scanner(connectionSocket.getInputStream());
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            request = inFromClient.nextLine(); //client request
            System.out.println("Received: "+request);

            /*dividing request command*/
            String reqMeth = request.substring(0, 3);
            String reqURL = request.substring(5, (request.lastIndexOf("HTTP/1.1")));
            String reqProto = request.substring(request.indexOf("HTTP/1.1"));
            System.out.println("Request Method:\t" +reqMeth +"\nRequest URL:\t" +reqURL+ "\nRequest Protocol: " +reqProto);

            File localFile = new File(reqURL.trim());
            FileReader in = new FileReader(localFile);
            BufferedReader inBuff = new BufferedReader(in);


            String c;
            while((c = inBuff.readLine())!=null){                   
                outToClient.writeBytes(c + '\n');                   
                System.out.println(c);
            } //END while
            outToClient.flush();
            in.close();


        } //END while(true)
      } //END main
} //END class

Here is the client code: 这是客户端代码:

import java.io.*;
import java.net.*;
import java.util.*;
public class TCPClient_file {

    public static void main(String[] args) throws Exception{
        String sentence ;
        Scanner inFromUser = new Scanner(System.in);
        Socket clientSocket = new Socket("192.168.0.16", 6790);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

        BufferedReader inFromServer = new BufferedReader(
                            new InputStreamReader(
                                    clientSocket.getInputStream()));

        sentence = inFromUser.nextLine();

        outToServer.writeBytes(sentence + '\n');

        String serverfile;

        while ((serverfile = inFromServer.readLine()) != null) 
            System.out.println(serverfile);

        inFromServer.close();   
        outToServer.close();
        clientSocket.close();
    }   //END main

}   //END class

Client request from server as such: 来自服务器的客户端请求:

GET /domains.txt HTTP/1.1

where "domains.txt" is a file on server containing a list of websites. 其中“ domains.txt”是服务器上包含网站列表的文件。

The while loop doesn't terminate because inFromServer is expecting more data. while循环不会终止,因为inFromServer需要更多数据。 You need to close the connection ( outToClient ) on the server side so that the client can be sure there is no more data coming. 您需要在服务器端关闭连接( outToClient ),以便客户端可以确保不再有其他数据。

One crude of achieving this is to send a trigger [String from server], after sending all the data to client, indicating completion of file transfer, at the client side you can check for this string and upon receiveing this string you can come out of your while loop and can close connection. 实现此目的的一个粗略方法是发送触发器[来自服务器的字符串],将所有数据发送到客户端后,表明文件传输已完成,在客户端可以检查该字符串,并且在接收到该字符串后就可以退出该触发器您的while循环并可以关闭连接。

Another better approach is, at the server-side before sending the actual file content send the size of the file and then the actual file data, on the client side keep track of bytes read, once you have read the byte equal to size posted earlier you can terminate your while loop 另一个更好的方法是,在服务器端发送实际文件内容之前,先发送文件的大小,然后再发送实际文件数据,在客户端,一旦读取的字节等于先前发布的大小,就跟踪读取的字节您可以终止while循环

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

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