我正在使用 ClientWebSocket 开发 Android 应用程序。
当我启动应用程序时,如果服务器正在运行,一切正常。
我停止服务器后,客户端无法重新连接到服务器,也无法接收消息。我注意到在我停止服务器后,clientwebsocket 的状态仍然是“打开”!
如果我启动应用程序然后启动服务器,客户端无法连接!
这是代码:
string ip = "192.168.1.142";
int port = 9000;
private const int ReceiveChunkSize = 1024;
private const int SendChunkSize = 1024;
private ClientWebSocket _ws;
private readonly Uri _uri;
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private readonly CancellationToken _cancellationToken;
准备客户端:
_ws = new ClientWebSocket ();
_ws.Options.KeepAliveInterval = TimeSpan.FromSeconds (20);
_uri = new Uri ("ws://"+ip+":"+port);
_cancellationToken = _cancellationTokenSource.Token;
连接方式:
public async void ConnectAsync()
{
await Task.Run (() => {
try {
var tk = _ws.ConnectAsync (_uri, _cancellationTokenSource.Token);
tk.Wait(4000);
if (tk.IsCompleted) {
//CallOnConnected ();
StartListen ();
}
}
catch
{
}
});
}
收听收入消息:
private async void StartListen()
{
var buffer = new byte[ReceiveChunkSize];
try
{
while (_ws.State == WebSocketState.Open)
{
var stringResult = new StringBuilder();
WebSocketReceiveResult result;
do
{
result = await _ws.ReceiveAsync(new ArraySegment<byte>(buffer), _cancellationToken);
if (result.MessageType == WebSocketMessageType.Close)
{
await
_ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
//CallOnDisconnected();
}
else
{
var str = Encoding.UTF8.GetString(buffer, 0, result.Count);
stringResult.Append(str);
}
} while (!result.EndOfMessage);
//CallOnMessage(stringResult);
}
}
catch (Exception)
{
//CallOnDisconnected();
}
finally
{
_ws.Dispose();
}
}
在 MainActivity 中,我使用计时器进行重新连接:
void Try_Connect(){
if ((my_clientwebsocket.Connection_Status == System.Net.WebSockets.WebSocketState.Open)|(my_clientwebsocket.Connection_Status == System.Net.WebSockets.WebSocketState.Connecting)) {
return;
}
new Thread (new ThreadStart (delegate {
RunOnUiThread (() => {
try {
my_clientwebsocket.ConnectAsync();
} catch {
}
});
})).Start ();
}
怎么了?!
感谢帮助