Connection/disconnection OK

This commit is contained in:
Crom (Thibaut CHARLES) 2015-05-01 18:30:39 +02:00
parent 72816ed1a7
commit 2a887f5142
2 changed files with 31 additions and 12 deletions

View File

@ -42,5 +42,8 @@ void main() {
sock.sendWait(`{"action":"bind","target":"testnpc"}`);
writeln(sock.receiveWait);
Thread.sleep(dur!"seconds"(1));
sock.shutdown(SocketShutdown.BOTH);
Thread.sleep(dur!"seconds"(1));
}

View File

@ -130,30 +130,46 @@ namespace CLRScript
void RequestHandler(IAsyncResult state)
{
Socket sockClient = sockServer.EndAccept(state);
sockServer.BeginAccept(new AsyncCallback(RequestHandler), null);
sockClient.Blocking = true;
while (sockClient.Connected) {
sockClient.Blocking = false;
if (sockClient.Available > 0) {
byte[] rawData = new byte[sockClient.Available];
sockClient.Receive(rawData, rawData.Length, 0);
try {
while (sockClient.Connected && IsSocketConnected(sockClient)) {
byte[] rawData = new byte[0];
byte[] buf = new byte[256];
int recv;
string data = Encoding.UTF8.GetString(rawData);
Debug("Queued "+data);
sockBufferIn.Enqueue(new Tuple<string,Socket>(data, sockClient));
while (sockClient.Available>0 && (recv = sockClient.Receive(buf))>0) {
rawData = rawData.Concat(buf.Take(recv)).ToArray();
Thread.Sleep(10);
}
if (rawData.Length > 0) {
string data = Encoding.UTF8.GetString(rawData);
Debug("Queued "+data);
sockBufferIn.Enqueue(new Tuple<string,Socket>(data, sockClient));
}
Thread.Sleep(100);
}
Thread.Sleep(10);
}
catch (Exception e) {
Debug(e.ToString());
}
//Remove stored bind
Debug("EXIT");
var sock = sockClients.First(kvp => kvp.Value==sockClient);
sockClients.Remove(sock.Key);
}
public static bool IsSocketConnected(Socket socket)
{
try { return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0); }
catch (SocketException) { return false; }
}
Socket sockServer;
Queue<Tuple<string,Socket>> sockBufferIn;//Request & client