.Net Core & Android Client Chat
Here is an example of a simple .NET Core application that uses SignalR to send messages between a server and an Android client:
Server:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.DependencyInjection; namespace MyApp { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSignalR(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapHub<ChatHub>("/chat"); }); } } public class ChatHub : Hub { public async Task SendMessage(string message) { await Clients.All.SendAsync("ReceiveMessage", message); } } } |
Android client:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import android.os.Bundle; import android.widget.EditText; import android.widget.TextView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.microsoft.signalr.HubConnection; import com.microsoft.signalr.HubConnectionBuilder; import java.util.concurrent.CompletionException; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private HubConnection hubConnection; private TextView messagesTextView; private EditText messageEditText; private FloatingActionButton sendButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); messagesTextView = findViewById(R.id.messages_text_view); messageEditText = findViewById(R.id.message_edit_text); sendButton = findViewById(R.id.send_button); hubConnection = HubConnectionBuilder.create("http://localhost:5000/chat").build(); hubConnection.on("ReceiveMessage", (message) -> { runOnUiThread(() -> { messagesTextView.setText(messagesTextView.getText() + "\n" + message); }); }, String.class); hubConnection.start().handle((result, exception) -> { if (exception != null) { throw new CompletionException(exception); } return result; }); sendButton.setOnClickListener((view) -> { String message = messageEditText.getText().toString(); hubConnection.send("SendMessage", message); messageEditText.setText(""); }); } } |
This example consists of a server and an Android client. The server is a .NET Core application that uses SignalR to send messages to all connected clients. The Android client is an app that connects to the server using the SignalR Java client library and displays messages received from the server.
Recent Comments