Skip to content

Instantly share code, notes, and snippets.

@ankeetmaini
ankeetmaini / index.js
Created December 12, 2022 05:19
Slow server
const html = (requestTime) => `<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Running Successfull</title>
</head>
<script>
@ankeetmaini
ankeetmaini / machine.js
Last active July 26, 2021 09:49
Generated by XState Viz: https://xstate.js.org/viz
var buttonMachine = Machine({
id: 'policy',
initial: 'activated',
states: {
activated: {
on: {
update: {
private void chat() throws InterruptedException {
DemoServiceGrpc.DemoServiceStub stub = DemoServiceGrpc.newStub(channel);
StreamObserver<ChatRequest> request = stub.chat(new StreamObserver<ChatResponse>() {
@Override
public void onNext(ChatResponse chatResponse) {
// called everytime server replies
System.out.println(chatResponse.getReply());
}
@Override
public StreamObserver<ChatRequest> chat(StreamObserver<ChatResponse> responseObserver) {
return new StreamObserver<ChatRequest>() {
@Override
public void onNext(ChatRequest chatRequest) {
// extract the message
String message = chatRequest.getMessage();
// create the response
ChatResponse response = ChatResponse.newBuilder()
.setReply("server says thanks for sending: " + message)
message ChatRequest {
string message = 1;
}
message ChatResponse {
string reply = 1;
}
service DemoService {
rpc Sum(SumRequest) returns (SumResponse);
rpc Chat(stream ChatRequest) returns (stream ChatResponse);
// step 1 - creating the channel
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 3000)
.usePlaintext()
.build();
// step 2 - creating the stub
DemoServiceGrpc.DemoServiceBlockingStub stub = DemoServiceGrpc.newBlockingStub(channel);
// request
SumRequest request = SumRequest.newBuilder()
public class Application {
public static void main(String[] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(3000)
.addService(new DemoServiceImpl())
.build();
server.start();
// boring boilerplate here
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
import io.grpc.stub.StreamObserver;
public class DemoServiceImpl extends DemoServiceGrpc.DemoServiceImplBase {
@Override
public void sum(SumRequest request, StreamObserver<SumResponse> responseObserver) {
int num1 = request.getNum1();
int num2 = request.getNum2();
int result = num1 + num2;
public class DemoServiceImpl extends DemoServiceGrpc.DemoServiceImplBase {
@Override
public void sum (SumRequest request, StreamObserver responseObserver) {
}
}
syntax = 'proto3' ;
message SumRequest {
int32 num1 = 1 ;
int32 num2 = 2 ;
}
message SumResponse {
int32 sum = 1 ;
}
service DemoService {
rpc Sum ( SumRequest ) returns ( SumResponse ) ;