简体   繁体   English

具有连续通信的Java套接字

[英]Java Sockets With Continuous Communication

I want to be able to do the following on the client side: 我希望能够在客户端执行以下操作:

  • Open socket 打开插座
  • Send Data 发送数据
  • Wait 等待
  • Send More Data 发送更多数据

And server side: 和服务器端:

  • Open msocket 打开msocket
  • Recive data Recive数据
  • Wait 等待
  • Keep recivieng (Loop over and over) 保持记忆(循环遍历)

Currently i cant make it loop :( 目前我不能让它循环:(

I have client side: 我有客户方:

Constctor: Constctor:

s = new Socket(ServerIPAddr, 6100);
out = new ObjectOutputStream(s.getOutputStream());

Looping function: 循环功能:

    public void sendImage(BufferedImage image){

    System.out.println("Starting to send");
    try {

        ImageIO.write(image, "PNG", out);
        System.out.println("Sent");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } // png is lossless

}

This can be called many times one after another. 这可以一个接一个地调用多次。

Server side i have consturctor: 服务器端我有consturctor:

    public ServerConnectionThread(Socket clientSocket) {current = clientSocket;}

Run function: 运行功能:

    public void run() {
    int i = 0;
    System.out.println("Connection accepted");
    System.out.println("Threaded spanwed");
    try {ObjectInputStream in = new ObjectInputStream(current.getInputStream());
        while (capturing) {
            ImageIO.write(ImageIO.read(in), "PNG", new File("test" + i++
                    + ".png"));
            in.close();
        }
    } catch (IOException e) {e.printStackTrace();}

}

Does anyone know why it only works for the first piece of data sent? 有谁知道为什么它只适用于发送的第一个数据? And refuses to continuosuly sending? 并拒绝连续发送?

-UPDATE- -UPDATE-

while (capturing) {
            BufferedImage b = ImageIO.read(in);
            if(b == null){
                continue;
            }
            ImageIO.write(b, "PNG", new File("test" + i++
                    + ".png"));

        }

Seems to fix this issue 似乎解决了这个问题

Why you are closing inputStream ? 为什么要关闭inputStream?

Try this - 尝试这个 -

 while (capturing) {
            ImageIO.write(ImageIO.read(in), "PNG", new File("test" + i++ ".png"));
            //in.close();
      }

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

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