简体   繁体   English

使用套接字循环输入流

[英]Loop with input stream using sockets

Java sending and receiving file (byte[]) over sockets Java通过套接字发送和接收文件(字节[])

referring to the above question i just wanted to ask how can i put this code in loop for recieving multiple images from client side ???? 提到上面的问题,我只想问一下我如何才能将此代码放入循环中以便从客户端接收多个图像? I have tried but it doesnot stop at (count = is.read(bytes)) > 0 once it has read first time. 我已经尝试过了,但是一旦它第一次读取,它就不会在(count = is.read(bytes))> 0处停止。 Pleas help 求助

I am not actually sure that I understand your question exactly, but I will try to help. 我实际上不确定我是否完全理解您的问题,但我会尽力提供帮助。 So you want to have connection client/server for infinite amount of time? 因此,您想无限期地连接客户端/服务器吗? So try making both the server client and the client itself as threads and then put the tread in a loop. 因此,尝试使服务器客户端和客户端本身都成为线程,然后将其循环。 Try this sample. 试试这个样本。

connection = new Socket("IP",PORT);
        input = new DataInputStream(connection.getInputStream());
        output = new DataOutputStream(connection.getOutputStream());
        new Thread(new Runnable() {

        public void run(){
            while(true){
            try
            {
                System.out.println(">>" + input.readUTF());
            }
            catch(Exception e){
                try
                {
                    input.close();
                    output.close();
                    connection.close();
                }
                catch(Exception e2)
                {}
             }
            }
        }
        }).start(); 

        Scanner scan = new Scanner(System.in);

        while(true)
        {
            String data = scan.nextLine();
            output.writeUTF(data);
        }

This is the code for the client. 这是客户端的代码。 You must also have ClienT Service thread that accepts all the data and sends back info! 您还必须具有ClienT服务线程,该线程接受所有数据并发回信息! Hope I was helpful, because I am not really sure I understood the question correctly. 希望我能有所帮助,因为我不确定我是否正确理解了这个问题。 Good Luck! 祝好运!

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

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