只能进行一次 gRPC 请求,然后应用程序就会冻结。

huangapple 未分类评论44阅读模式
英文:

Can only make one grpc request then application freezes

问题

以下是您提供的内容的翻译部分:

服务器端实现的方法:

package CarParkOperations.proto.cp;

// ... 导入省略 ...

public class CarParkService extends carParkServiceGrpc.carParkServiceImplBase {
    // ... 其他代码省略 ...

    public void showStatus(carparkRequest request, StreamObserver<carParkResponse> rStreamObserver) {
        // ... 代码省略 ...
    }

    @Override
    public void allCarParks(allCarp rAllCarp, StreamObserver<carParkResponse> rStreamObserver) {
        // ... 代码省略 ...
    }

    public void setFull(CarParkToUpdateRequest request, StreamObserver<carParkResponse> rStreamObserver) {
        // ... 代码省略 ...
    }

    public void setSpaces(CarParkToUpdateRequest request, StreamObserver<carParkResponse> rStreamObserver) {
        // ... 代码省略 ...
    }
}

客户端实现的方法:

// ... 导入省略 ...

public class YourClientClass {
    // ... 其他代码省略 ...

    public void showStatus(int id) {
        // ... 代码省略 ...
    }

    public void setFull(int id) {
        // ... 代码省略 ...
    }

    public void allCarParks(String status) {
        // ... 代码省略 ...
    }

    public void setSpaces(int id) {
        // ... 代码省略 ...
    }
}

Proto 文件:

syntax = "proto3";

package CarParkOperations;

// ... 其他选项省略 ...

service carParkService {
    rpc showStatus(carparkRequest) returns (carParkResponse) {};
    rpc setFull(CarParkToUpdateRequest) returns (carParkResponse) {};
    rpc setSpaces(CarParkToUpdateRequest) returns (carParkResponse) {};
    rpc allCarParks(allCarp) returns (stream carParkResponse) {};
}

message CarPark {
    int32 carPark_id = 1;
    string status = 2;
    string location = 3;
}

message carparkRequest {
    int32 carPark_id = 1;
}

message CarParkToUpdateRequest {
    int32 device_id = 1;
}

message allCarp {
    string status = 1;
}

message carParkResponse {
    CarPark carPark = 1;
}

希望这些翻译能对您有所帮助。如果您有更多的问题或需要进一步的帮助,请随时提问。

英文:

I am trying to implement a client and server using grpc. When I send a request to the server I get a response but when I try and send another request the application freezes or just continuously says it is looking for the Item that I requested. I'm very new to this so dont know what is going on. this is the methods that I have implemented in my server:

package CarParkOperations.proto.cp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.util.Collection;

public class CarParkService extends carParkServiceGrpc.carParkServiceImplBase{
	private static final Logger logger = Logger.getLogger(CarParkService.class.getName());
	
	
	
	 private Server server;
	 
	 private void start() throws IOException {
		    /* The port on which the server should run */
		    int port = 3000;
		    
		    server = ServerBuilder.forPort(port)
		        .addService(new CarParkService())
		        .build()
		        .start();
		    
		    logger.info(&quot;Server started, listening on &quot; + port);
		    
		    Runtime.getRuntime().addShutdownHook(new Thread() {
		      @Override
		      public void run() {
		        System.err.println(&quot;*** shutting down gRPC server since JVM is shutting down&quot;);
		        CarParkService.this.stop();
		        System.err.println(&quot;*** server shut down&quot;);
		      }
		    });
		  }

		  private void stop() {
		    if (server != null) {
		      server.shutdown();
		    }
		  }

		  /**
		   * Await termination on the main thread since the grpc library uses daemon threads.
		   */
		  private void blockUntilShutdown() throws InterruptedException {
		    if (server != null) {
		      server.awaitTermination();
		    }
		  }

		  /**
		   * Main launches the server from the command line.
		   */
		  public static void main(String[] args) throws IOException, InterruptedException {
		    final CarParkService server = new CarParkService();
		    server.start();
		    server.blockUntilShutdown();
		  }
	
	public void showStatus(carparkRequest request, StreamObserver&lt;carParkResponse&gt; rStreamObserver) {
		for(CarParkOperations.proto.cp.CarPark c : Car.getInstance()) {
			if(c.getCarParkId() == request.getCarParkId()) {
				carParkResponse response = carParkResponse.newBuilder().setCarPark(c).build();
				rStreamObserver.onNext(response);
				rStreamObserver.onCompleted();
				return;
			}
		}	
	}

    @Override
    public void allCarParks(allCarp rAllCarp, StreamObserver&lt;carParkResponse&gt; rStreamObserver) {
    	ArrayList&lt;CarParkOperations.proto.cp.CarPark&gt; carList = Car.getInstance();
    	for (CarParkOperations.proto.cp.CarPark car : Car.carparkCar) {
    		carParkResponse response = carParkResponse.newBuilder().setCarPark(car).build();
    			if(car.getStatus() == rAllCarp.getStatus()) {
    				rStreamObserver.onNext(response);
    			}
    	}
    	rStreamObserver.onCompleted();
    }
	
	public void setFull(CarParkToUpdateRequest request, StreamObserver&lt;carParkResponse&gt; rStreamObserver) {
		ArrayList&lt;CarParkOperations.proto.cp.CarPark&gt; carList = Car.getInstance();
			for(CarParkOperations.proto.cp.CarPark c : carList) {
				if(c.getCarParkId() == request.getDeviceId()) {
					Car.carparkCar.clear();
					Car.carparkCar.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(c.getCarParkId()).setLocation(c.getLocation()).setStatus(&quot;Full&quot;).build());
					for(CarParkOperations.proto.cp.CarPark car : Car.carparkCar) {
						carParkResponse response = carParkResponse.newBuilder().setCarPark(car).build();
						rStreamObserver.onNext(response);
						rStreamObserver.onCompleted();
						return;
					}
				}
			}
	}
	public void setSpaces(CarParkToUpdateRequest request, StreamObserver&lt;carParkResponse&gt; rStreamObserver) {
		ArrayList&lt;CarParkOperations.proto.cp.CarPark&gt; carList = Car.getInstance();
		for(CarParkOperations.proto.cp.CarPark c : carList) {
			if(c.getCarParkId() == request.getDeviceId()) {
				Car.carparkCar.clear();
				Car.carparkCar.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(c.getCarParkId()).setLocation(c.getLocation()).setStatus(&quot;Spaces&quot;).build());
				for(CarParkOperations.proto.cp.CarPark car : Car.carparkCar) {
					carParkResponse response = carParkResponse.newBuilder().setCarPark(car).build();
					rStreamObserver.onNext(response);
					rStreamObserver.onCompleted();
					return;
				}
			}
		}	
	}
	
}

These are the methods I implemented in my client:

	 public void showStatus(int id) {
		  channel =ManagedChannelBuilder.forAddress(&quot;localhost&quot;, 3000)
			        // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
			        // needing certificates.
			        .usePlaintext()
			        .build();
		  blockingStub = carParkServiceGrpc.newBlockingStub(channel);
		    asyncStub = carParkServiceGrpc.newStub(channel);
			 logger.info(&quot;Will try to get CarPark &quot; + id + &quot; ...&quot;);
			 carparkRequest request = carparkRequest.newBuilder().setCarParkId(id).build();
			 carParkResponse response;
			 try {
				 response = blockingStub.showStatus(request);
			 }catch(StatusRuntimeException e) {
				 logger.log(Level.WARNING, &quot;RPC failed: {0}&quot;, e.getStatus());
			      return;
			 }finally {
				channel.shutdown();
			}
			 logger.info(&quot;Carpark: &quot; + response.getCarPark());
			statusArea.append(response.getCarPark().toString());
	 }
	 
	 
	 
	 
	 
	 public void setFull(int id) {
		  channel =ManagedChannelBuilder.forAddress(&quot;localhost&quot;, 3000)
			        // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
			        // needing certificates.
			        .usePlaintext()
			        .build();
		  blockingStub = carParkServiceGrpc.newBlockingStub(channel);
		  asyncStub = carParkServiceGrpc.newStub(channel);
			 logger.info(&quot;Will try to get CarPark &quot; + id + &quot; ...&quot;);
			 CarParkToUpdateRequest request = CarParkToUpdateRequest.newBuilder().setDeviceId(id).build();
			 carParkResponse response;
			 try {
				 response = blockingStub.setFull(request);
			 }catch(StatusRuntimeException e) {
				 logger.log(Level.WARNING, &quot;RPC failed: {0}&quot;, e.getStatus());
			      return;
			 }finally {
				channel.shutdown();
			 }
			 logger.info(&quot;Carpark: &quot; + response.getCarPark());
			 fullArea.append(response.getCarPark().toString());
	 }
	 
	 
	 
	 
	
	 public void allCarParks(String status) {
		 channel =ManagedChannelBuilder.forAddress(&quot;localhost&quot;, 3000)
			        // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
			        // needing certificates.
			        .usePlaintext()
			        .build();
		  	blockingStub = carParkServiceGrpc.newBlockingStub(channel);
		    asyncStub = carParkServiceGrpc.newStub(channel);
			 logger.info(&quot;Will try to get CarPark &quot; + status + &quot; ...&quot;);

			 allCarp request =
					 allCarp.newBuilder().setStatus(status).build();
		    Iterator&lt;carParkResponse&gt; carResponse;
		    try {
		    	carResponse = blockingStub.allCarParks(request);
		      for (int i = 1; carResponse.hasNext(); i++) {
		    	  carParkResponse carResponse1 = carResponse.next();
		    	  info(&quot;Result #&quot; + i + &quot;: {0}&quot;, carResponse1);
		        if (testHelper != null) {
		          testHelper.onMessage(carResponse1);
		        }
		      }
		    } catch(StatusRuntimeException e) {
				 logger.log(Level.WARNING, &quot;RPC failed: {0}&quot;, e.getStatus());
			      return;
		    }
		  }
	 public void setSpaces(int id) {
		  channel =ManagedChannelBuilder.forAddress(&quot;localhost&quot;, 3000)
			        // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
			        // needing certificates.
			        .usePlaintext()
			        .build();
		  blockingStub = carParkServiceGrpc.newBlockingStub(channel);
		    asyncStub = carParkServiceGrpc.newStub(channel);
			 logger.info(&quot;Will try to get CarPark &quot; + id + &quot; ...&quot;);
			 CarParkToUpdateRequest request = CarParkToUpdateRequest.newBuilder().setDeviceId(id).build();
			 carParkResponse response;
			 try {
				 response = blockingStub.setSpaces(request);
			 }catch(StatusRuntimeException e) {
				 logger.log(Level.WARNING, &quot;RPC failed: {0}&quot;, e.getStatus());
			      return;
			 }finally {
					channel.shutdown();
				}
			 logger.info(&quot;Carpark: &quot; + response.getCarPark());
			 spacesArea.append(response.getCarPark().toString());
	 }

And this is the proto file:

syntax = &quot;proto3&quot;;

package CarParkOperations;

option java_package = &quot;CarParkOperations.proto.cp&quot;;
option java_multiple_files = true;
option java_outer_classname = &quot;ClassName&quot;;

service carParkService{
rpc showStatus(carparkRequest) returns (carParkResponse) {};
rpc setFull(CarParkToUpdateRequest) returns (carParkResponse){};
rpc setSpaces(CarParkToUpdateRequest) returns (carParkResponse){};
rpc allCarParks(allCarp) returns (stream carParkResponse){};
}

message CarPark{
int32 carPark_id = 1;
string status =2;
string location =3;

}

message carparkRequest{
int32 carPark_id = 1;
}

message CarParkToUpdateRequest {
 int32 device_id = 1;
}
message allCarp{
string status = 1;
}


message carParkResponse{
CarPark carPark =1;
}

Like i said I can get a resonse back when I fill in the right request(except for the allCarParks method but thats a separate issue) but when I try do another request is gets stuck. I can send a second response the odd time but thats it. I just want to know where I'm going wrong. Any help would be much appreciated.

答案1

得分: 0

在您的服务器端实现中,不必始终调用onNext()和onCompleted(),例如当列表为空或某些条件不满足时,就会出现错误。

英文:

In your server side implementation, onNext() and onCompleted() are not always to be called, for example when the list is empty or some condition is not met, that's the bug.

huangapple
  • 本文由 发表于 2020年4月4日 09:56:08
  • 转载请务必保留本文链接:https://java.coder-hub.com/61022882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定