양방향 스트리밍
클라이언트와 서버가 동시에 메시지 시퀀스를 주고받을 수 있는 양방향 스트리밍을 능숙하게 구현합니다.
양방향 스트리밍은(는) CoddyKit의 무료 gRPC & High Performance APIs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 gRPC & High Performance APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. gRPC & High Performance APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Bidirectional Streaming: Two-Way Talk
What if both sides in a conversation could speak and listen at the same time? That's bidirectional streaming in gRPC! It allows both the client and server to send a sequence of messages to each other, concurrently.
Why Use Bidi Streaming?
Bidirectional streaming is perfect for applications needing real-time, interactive communication. Think of it like a phone call where both parties can talk and hear simultaneously.
- Chat applications: Users send and receive messages instantly.
- Live updates: Servers push data to clients as events happen.
- Gaming: Synchronized game state updates between players and server.
Defining a Bidi Stream Service
To enable bidirectional streaming, you use the stream keyword for both the request and response types in your .proto file.
This tells gRPC that the method will handle a continuous flow of messages in both directions.
syntax = "proto3";
package chat;
message ChatMessage {
string user = 1;
string message = 2;
}
service ChatService {
rpc Chat(stream ChatMessage) returns (stream ChatMessage);
}Server: Receiving Client Messages
On the server, your service method will receive a StreamObserver for the incoming client messages. You'll implement its methods to process each message.
onNext(msg): Called for each message from the client.onError(t): Called if the client stream encounters an error.onCompleted(): Called when the client finishes sending messages.
Server: Sending Back Responses
The server also gets a StreamObserver (usually named responseObserver) to send messages back to the client. This allows the server to push multiple responses.
responseObserver.onNext(resp): Sends a message to the client.responseObserver.onError(t): Signals an error to the client.responseObserver.onCompleted(): Closes the server's outgoing stream.
Client: Starting the Conversation
On the client, you'll use an asynchronous (non-blocking) stub to call the streaming method. This call immediately returns a StreamObserver.
This returned observer is what the client uses to send messages to the server.
Client: Two-Way Communication
The client needs two main parts for bidirectional streaming:
- An observer for outgoing messages: This is used to
onNext()messages to the server. - An observer for incoming messages: This is passed to the gRPC call to handle responses from the server.
Both streams operate independently and concurrently.
Full Server Bidi Stream Example
Here's a simplified gRPC server that echoes messages received from the client. Remember to compile your .proto file and include gRPC dependencies.
Try running this example:
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
// Assuming ChatServiceGrpc and ChatMessage are generated
// from the proto definition.
import chat.ChatServiceGrpc;
import chat.ChatMessage;
public class ChatServer {
public static void main(String[] args) throws Exception {
Server server = ServerBuilder.forPort(50051)
.addService(new ChatServiceImpl())
.build();
server.start();
System.out.println("Server started on port 50051");
server.awaitTermination();
}
static class ChatServiceImpl extends ChatServiceGrpc.ChatServiceImplBase {
@Override
public StreamObserver<ChatMessage> chat(
final StreamObserver<ChatMessage> responseObserver) {
return new StreamObserver<ChatMessage>() {
@Override
public void onNext(ChatMessage request) {
// Received a message from the client
System.out.println("Server received: " + request.getMessage());
// Echo it back to the client
ChatMessage response = ChatMessage.newBuilder()
.setUser("Server")
.setMessage("Echo: " + request.getMessage())
.build();
responseObserver.onNext(response);
}
@Override
public void onError(Throwable t) {
System.err.println("Server error: " + t.getMessage());
}
@Override
public void onCompleted() {
System.out.println("Client stream completed.");
responseObserver.onCompleted(); // Close server stream
}
};
}
}
}Full Client Bidi Stream Example
This client sends a few messages and listens for responses. Run the server first, then this client. The client will send messages and print the server's echoes.
Try running this example:
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
// Assuming ChatServiceGrpc and ChatMessage are generated
// from the proto definition.
import chat.ChatServiceGrpc;
import chat.ChatMessage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class ChatClient {
public static void main(String[] args) throws Exception {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051)
.usePlaintext() // For demonstration, use TLS in production
.build();
ChatServiceGrpc.ChatStub asyncStub = ChatServiceGrpc.newStub(channel);
CountDownLatch finishLatch = new CountDownLatch(1);
StreamObserver<ChatMessage> requestObserver = asyncStub.chat(
new StreamObserver<ChatMessage>() {
@Override
public void onNext(ChatMessage response) {
System.out.println("Client received: " + response.getMessage());
}
@Override
public void onError(Throwable t) {
System.err.println("Client error: " + t.getMessage());
finishLatch.countDown();
}
@Override
public void onCompleted() {
System.out.println("Server stream completed.");
finishLatch.countDown();
}
});
try {
// Client sends messages
for (int i = 0; i < 3; i++) {
ChatMessage request = ChatMessage.newBuilder()
.setUser("Client")
.setMessage("Hello " + i)
.build();
requestObserver.onNext(request);
Thread.sleep(500); // Simulate delay
}
} catch (RuntimeException | InterruptedException e) {
requestObserver.onError(e);
throw e;
} finally {
requestObserver.onCompleted(); // Client finishes sending
}
if (!finishLatch.await(1, TimeUnit.MINUTES)) {
System.err.println("Client timed out waiting for server response.");
}
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}
}Bidirectional Stream Check
You've learned about bidirectional streaming. Which statement best describes how both client and server communicate in a gRPC bidirectional stream?
Bidirectional Streaming Recap
Great job! You've mastered bidirectional streaming in gRPC.
- It enables both client and server to send sequences of messages.
- Ideal for real-time, interactive applications like chat.
- Defined using the
streamkeyword for both request and response in Protobuf. - Requires separate logic on both client and server to manage incoming and outgoing message streams.
This powerful pattern opens up many possibilities for highly responsive distributed systems.
자주 묻는 질문
“양방향 스트리밍” 강의는 무료인가요?
네 — “양방향 스트리밍” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 gRPC & High Performance APIs 강의 전체를 잠금 해제할 수 있습니다. gRPC & High Performance APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“양방향 스트리밍”에서 뭘 배우나요?
클라이언트와 서버가 동시에 메시지 시퀀스를 주고받을 수 있는 양방향 스트리밍을 능숙하게 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 gRPC & High Performance APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
gRPC & High Performance APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 gRPC & High Performance APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“양방향 스트리밍” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 gRPC & High Performance APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 gRPC & High Performance APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.