我有一个 SignalR 服务器正在运行
http://localhost:50926/testhub
我可以使用 .net signalR 客户端连接到同一台机器上的集线器,它可以按预期工作。我无法在 Android Studio 中运行的 Android 客户端上连接到它。我知道您无法从模拟器连接到本地主机,因此我设置了一个 ng rock 代理,代理似乎从邮递员连接到本地主机,但我无法从模拟器连接。我知道 android 客户端只能使用 websockets,所以我已将集线器配置为使用这样的 web sockets:
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseWebSockets();
app.UseSignalR((configure) =>
{
var desiredTransports =
HttpTransportType.WebSockets;
configure.MapHub<TestHub>("/testhub", (options) =>
{
options.Transports = desiredTransports;
});
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
这是我的 Android 客户端代码:
public class MainActivity extends AppCompatActivity {
HubConnection hubConnection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hubConnection = HubConnectionBuilder.create("http://c03e07e9.ngrok.io/testhub").build();
hubConnection.start();
if (hubConnection.getConnectionState()== HubConnectionState.CONNECTED){
hubConnection.send("ReceiveMessage","hello from android");
}
}
和毕业典礼:
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.ct.sigrtest2"
minSdkVersion 28
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.microsoft.signalr:signalr:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.2'
android 客户端不会抛出任何错误,也不会连接到 ngrok 谁能告诉我为什么我无法连接到集线器?