private void OnClientAccepted(Socket socket) { var client = new CClientSocket(socket); var realClient = CreateClient(client); Logger.Write(LogLevel.Info, "[{0}] Accepted {1}", Name, client.Host); client.OnPacket += (packet) => Enqueue(() => HandlePacket(realClient, packet)); client.OnDisconnected += () => Enqueue(() => HandleDisconnect(realClient)); Enqueue(() => client.Initialize(Constants.Version)); }
public CConnection(string host, int port) { ClientSocket = new CClientSocket(host, port); ClientSocket.OnClientConnected += ClientSocket_OnClientConnected; ClientSocket.OnClientDisconnected += ClientSocket_OnClientDisconnected; ClientSocket.OnClientReceivedData += ClientSocket_OnClientReceivedData; PacketCallbacks = new List <SPacketCallback>(); InitPacketCallbacks(); SyncCallbacks = new List <SSyncCallback>(); InitSyncCallbacks(); }
void AddConnection(CClientSocket ClientSocket) { SConnection connection = new SConnection { ClientSocket = ClientSocket, ConnectionType = EConnectionType.Unknown }; lock (Connections) { Connections.Add(connection); } }
/// <summary> /// Unlock a previously locked socket to pool for reuse. /// </summary> /// <param name="handler">A previously locked socket</param> public virtual void Unlock(CClientSocket cs) { uint poolId; if (cs == null) { return; } lock (m_cs) { poolId = m_nPoolId; } ClientCoreLoader.UnlockASocket(poolId, cs.Handle); }
public MapleClient(Socket session) { SClient = new CClientSocket(this, session); Host = SClient.Host; Port = SClient.Port; ServerConsole.Info(String.Format("{0}:{1} Connnected", Host, Port)); Channel = 1; Connected = true; LastPacketsSent = new LimitedQueue <PacketWriter>(10); CheatTracker = new OffenceTracker() { Client = this }; }
void RemoveConnection(CClientSocket ClientSocket) { lock (Connections) { for (int i = 0; i < Connections.Count; i++) { if (Connections[i].ClientSocket == ClientSocket) { Connections.RemoveAt(i); break; } } } }
static void Main(string[] args) { bool ok; CClientSocket.QueueConfigure.MessageQueuePassword = "******"; if (System.Environment.OSVersion.Platform == PlatformID.Unix) { CClientSocket.QueueConfigure.WorkDirectory = "/home/yye/sp_test/"; } else { CClientSocket.QueueConfigure.WorkDirectory = "c:\\sp_test"; } Console.WriteLine("This is a client. Remote router host: "); CConnectionContext cc = new CConnectionContext(Console.ReadLine(), 20901, "lb_client", "pwd_lb_client"); using (CSocketPool <Pi> spPi = new CSocketPool <Pi>(true)) //true -- automatic reconnecting { ok = spPi.StartSocketPool(cc, 1, 1); CClientSocket cs = spPi.Sockets[0]; //use persistent queue to ensure auto failure recovery and at-least-once or once-only delivery ok = cs.ClientQueue.StartQueue("pi_queue", 24 * 3600, (cs.EncryptionMethod == tagEncryptionMethod.TLSv1)); cs.ClientQueue.RoutingQueueIndex = true; Pi pi = spPi.AsyncHandlers[0]; pi.WaitAll(); //make sure all existing queued requests are processed before executing next requests double dPi = 0.0; int nDivision = 1000; int nNum = 10000000; double dStep = 1.0 / nNum / nDivision; int nReturns = 0; for (int n = 0; n < nDivision; ++n) { double dStart = (double)n / nDivision; ok = pi.SendRequest(piConst.idComputePi, dStart, dStep, nNum, (ar) => { double res; ar.Load(out res); dPi += res; ++nReturns; }); } ok = pi.WaitAll(); Console.WriteLine("Your pi = {0}, returns = {1}", dPi, nReturns); Console.WriteLine("Press ENTER key to shutdown the demo application ......"); Console.ReadLine(); } }
public void raise(ushort req_id) { CClientSocket cs = Socket; int ec = cs.ErrorCode; if (ec != 0) { string em = cs.ErrorMsg; throw new CSocketError(ec, em, req_id, true); } else { throw new CSocketError(SESSION_CLOSED_BEFORE, SESSION_CLOSED_BEFORE_ERR_MSG, req_id, true); } }
/// <summary> /// Put back original asynchronous handler into socket pool for reuse. You must call this method after calling LockByMyAlgorithm /// </summary> /// <param name="sql">A handler originated from LockByMyAlgorithm</param> public void UnlockByMyAlgorithm(CSql sql) { if (sql == null) { return; } CClientSocket cs = sql.AttachedClientSocket; lock (m_cs) { if (!m_dicSocketHandler.ContainsKey(cs)) { m_dicSocketHandler[cs] = sql; System.Threading.Monitor.PulseAll(m_cs); } } }
internal bool Verify(CClientSocket cs) { int errCode; IUcert cert = cs.UCert; string res = cert.Verify(out errCode); //do ssl server certificate authentication here if (errCode == 0) { return(true); } if (m_KeysAllowed != null) { return(m_KeysAllowed.IndexOf(ToStr(cert.PublicKey)) != -1); } return(false); }
private void SetQueue(CClientSocket socket) { int index = 0; foreach (CClientSocket cs in m_dicSocketHandler.Keys) { if (cs == socket) { if (m_qName.Length > 0) { if (!cs.ClientQueue.Available) { cs.ClientQueue.StartQueue(m_qName + index.ToString(), DEFAULT_QUEUE_TIME_TO_LIVE, cs.EncryptionMethod != tagEncryptionMethod.NoEncryption); } } break; } ++index; } }
public Form1() { InitializeComponent(); btnConnect.Click += (o, e) => { txbData.Text = string.Format("Connect to: {0}:{1}", txbAddress.Text, nmPort.Value); soc = new CClientSocket(txbAddress.Text, (int)nmPort.Value); soc.OnConnect += (_soc) => { Invoke((MethodInvoker) delegate { txbData.AppendText(string.Format("Socket {0} is connected", _soc.RemoteEndPoint.ToString())); //btnConnect.Text = "Disconnect"; }); }; soc.OnRead += (_soc) => { Invoke((MethodInvoker) delegate { txbData.AppendText(string.Format("Receive {0}:: Data: {1}", _soc.ToString(), soc.ReceivedText)); }); }; soc.OnDisconnect += (_soc) => { Invoke((MethodInvoker) delegate { txbData.AppendText(string.Format("Disconnect {0}", _soc.ToString())); //btnConnect.Text = "Connect"; }); }; soc.Connect(); }; btnSend.Click += (o, e) => { soc.SendText(txbSend.Text); }; }
void OnControllerIntroductionCallback(CClientSocket ClientSocket, int ConnectionIndex, byte[] arguments) { SControllerIntroduction ControllerIntroduction = (SControllerIntroduction)CSerialization.Deserialize <SControllerIntroduction>(arguments); SControllerAnswer ControllerAnswer = new SControllerAnswer { IsAuthorized = false, key = -1 }; SConnection Connection = Connections[ConnectionIndex]; if (ControllerIntroduction.Password != Program.ControllerPassword) { //Tell the controller that password was not accepted Connection.ClientSocket.SendPacket <SControllerAnswer>((byte)EControllerPackets.Introduction, ControllerAnswer); //At this stage the password is not valid, so we disconnect the invalid controller ClientSocket.Disconnect(); return; } int key = GenerateKeyForController(); //Authorize connection SControllerInformation ControllerInformation = (SControllerInformation)Connection.Information; ControllerInformation.IsAuthorized = true; ControllerInformation.Key = key; Connection.Information = (object)ControllerInformation; Connections[ConnectionIndex] = Connection; //Key for controlling clients ControllerAnswer.key = key; ControllerAnswer.IsAuthorized = true; //Tell the controller that he is authorized Connection.ClientSocket.SendPacket <SControllerAnswer>((byte)EControllerPackets.Introduction, ControllerAnswer); }
void OnControllerSessionCallback(CClientSocket ClientSocket, int ConnectionIndex, byte[] arguments) { SSessionPacket SessionPacket = CSerialization.Deserialize <SSessionPacket>(arguments); //Relay the session packet to the appropriate client foreach (SConnection Connection in Connections) { if (Connection.ConnectionType != EConnectionType.Client) { continue; } if (Connection.Information == null) { continue; } if (Connection.ClientSocket.GetHandle() == SessionPacket.ClientHandle) { Connection.ClientSocket.SendPacket <SSessionPacket>((byte)EClientPackets.Session, SessionPacket); break; } } }
private bool Transfer() { int index = 0; DAsyncResultHandler rh = null; DOnExceptionFromServer se = null; CClientSocket cs = AttachedClientSocket; if (!cs.Sendable) { return(false); } uint sent_buffer_size = cs.BytesInSendingBuffer; if (sent_buffer_size > 3 * STREAM_CHUNK_SIZE) { return(true); } while (index < m_vContext.Count) { CContext context = m_vContext[index]; if (context.Sent) { ++index; continue; } if (context.Uploading && context.Tried && context.File == null) { if (index == 0) { if (context.Upload != null) { context.Upload(this, CANNOT_OPEN_LOCAL_FILE_FOR_READING, context.ErrMsg); } m_vContext.RemoveFromFront(); } else { ++index; } continue; } if (context.Uploading) { if (!context.Tried) { context.Tried = true; try { FileShare fs = FileShare.None; if ((context.Flags & FILE_OPEN_SHARE_READ) == FILE_OPEN_SHARE_READ) { fs = FileShare.Read; } context.File = new FileStream(context.LocalFile, FileMode.Open, FileAccess.Read, fs); context.FileSize = context.File.Length; IClientQueue cq = AttachedClientSocket.ClientQueue; if (cq.Available) { if (!cq.StartJob()) { context.File.Close(); context.File = null; throw new Exception("Cannot start queue job"); } } if (!SendRequest(idUpload, context.FilePath, context.Flags, context.FileSize, rh, context.Discarded, se)) { return(false); } } catch (Exception err) { context.ErrMsg = err.Message; } finally { } } if (context.File == null) { if (index == 0) { if (context.Upload != null) { context.Upload(this, CANNOT_OPEN_LOCAL_FILE_FOR_READING, context.ErrMsg); } m_vContext.RemoveFromFront(); } else { ++index; } continue; } else { using (CScopeUQueue sb = new CScopeUQueue()) { if (sb.UQueue.MaxBufferSize < STREAM_CHUNK_SIZE) { sb.UQueue.Realloc(STREAM_CHUNK_SIZE); } byte[] buffer = sb.UQueue.IntenalBuffer; int ret = context.File.Read(buffer, 0, (int)STREAM_CHUNK_SIZE); while (ret > 0) { if (!SendRequest(idUploading, buffer, (uint)ret, rh, context.Discarded, se)) { return(false); } sent_buffer_size = cs.BytesInSendingBuffer; if (ret < (int)STREAM_CHUNK_SIZE) { break; } if (sent_buffer_size >= 5 * STREAM_CHUNK_SIZE) { break; } ret = context.File.Read(buffer, 0, (int)STREAM_CHUNK_SIZE); } if (ret < (int)STREAM_CHUNK_SIZE) { context.Sent = true; if (!SendRequest(idUploadCompleted, rh, context.Discarded, se)) { return(false); } IClientQueue cq = AttachedClientSocket.ClientQueue; if (cq.Available) { cq.EndJob(); } } if (sent_buffer_size >= 4 * STREAM_CHUNK_SIZE) { break; } } } } else { if (!SendRequest(idDownload, context.FilePath, context.Flags, rh, context.Discarded, se)) { return(false); } context.Sent = true; context.Tried = true; sent_buffer_size = cs.BytesInSendingBuffer; if (sent_buffer_size > 3 * STREAM_CHUNK_SIZE) { break; } } ++index; } return(true); }
void UploadEmployees(CUQueue q, ulong reqIndex) { uint ret; KeyValuePair <int, string> error = new KeyValuePair <int, string>(); ss.CInt64Array vId = new ss.CInt64Array(); CDBVariantArray vData; q.Load(out vData); if (vData.Count == 0) { ret = SendResultIndex(reqIndex, ss.Consts.idUploadEmployees, (int)0, "", vId); return; } else if ((vData.Count % 3) != 0) { ret = SendResultIndex(reqIndex, ss.Consts.idUploadEmployees, (int)-1, "Data array size is wrong", vId); return; } //use master for insert, update and delete var handler = CYourServer.Master.Lock(); //use Lock and Unlock to avoid SQL stream overlap on a session within a multi-thread environment if (handler == null) { ret = SendResultIndex(reqIndex, ss.Consts.idUploadEmployees, (int)-2, "No connection to a master database", vId); return; } CClientSocket cs = handler.AttachedClientSocket; do { if (!handler.BeginTrans() || !handler.Prepare("INSERT INTO mysample.EMPLOYEE(CompanyId,Name,JoinDate)VALUES(?,?,?)")) { break; } bool ok = true; CDBVariantArray v = new CDBVariantArray(); int rows = vData.Count / 3; for (int n = 0; n < rows; ++n) { v.Add(vData[n * 3 + 0]); v.Add(vData[n * 3 + 1]); v.Add(vData[n * 3 + 2]); ok = handler.Execute(v, (h, r, err, affected, fail_ok, vtId) => { if (r != 0) { if (error.Key == 0) { error = new KeyValuePair <int, string>(r, err); } vId.Add(-1); } else { vId.Add(long.Parse(vtId.ToString())); } }); if (!ok) { break; } v.Clear(); } if (!ok) { break; } ulong peer_handle = Handle; if (!handler.EndTrans(tagRollbackPlan.rpRollbackErrorAll, (h, res, errMsg) => { //send result if front peer not closed yet if (peer_handle == Handle) { if (res != 0 && error.Key == 0) { error = new KeyValuePair <int, string>(res, errMsg); } ret = SendResultIndex(reqIndex, ss.Consts.idUploadEmployees, error.Key, error.Value, vId); } }, (h, canceled) => { //send error message if front peer not closed yet if (peer_handle == Handle) { //socket closed after requests are put on wire if (error.Key == 0) { error = new KeyValuePair <int, string>(cs.ErrorCode, cs.ErrorMsg); } ret = SendResultIndex(reqIndex, ss.Consts.idUploadEmployees, error.Key, error.Value, vId); } })) { break; } //put handler back into pool as soon as possible for reuse as long as socket connection is not closed yet CYourServer.Master.Unlock(handler); return; } while (false); ret = SendResultIndex(reqIndex, ss.Consts.idUploadEmployees, cs.ErrorCode, cs.ErrorMsg, vId); }
private void ServerSocket_OnClientConnected(CClientSocket ClientSocket) { AddConnection(ClientSocket); }
private void ServerSocket_OnClientDisconnect(CClientSocket ClientSocket) { RemoveConnection(ClientSocket); }
protected ClientBase(CClientSocket socket) { m_socket = socket; }
internal CUCertImpl(CClientSocket cs) { m_cs = cs; IntPtr p = ClientCoreLoader.GetUCert(cs.Handle); if (p != IntPtr.Zero) { CertInfoIntenal cii = new CertInfoIntenal(); System.Runtime.InteropServices.Marshal.PtrToStructure(p, cii); Set(cii); } }
protected abstract TClient CreateClient(CClientSocket socket);
internal CPushImpl(CClientSocket cs) { m_cs = cs; }
protected override void OnPostProcessing(uint hint, ulong data) { uint d = 0; DAsyncResultHandler rh = null; System.Threading.Monitor.Enter(m_csFile); foreach (CContext it in m_vContext) { if (d >= m_MaxDownloading) { break; } if (it.File != null) { if (it.Uploading) { break; } else { ++d; continue; } } if (it.HasError) { continue; } if (it.Uploading) { OpenLocalRead(it); if (!it.HasError) { if (!SendRequest(idUpload, it.FilePath, it.Flags, it.FileSize, rh, it.Discarded, it.Se)) { CClientSocket cs = Socket; it.ErrCode = cs.ErrorCode; if (it.ErrCode == 0) { it.ErrCode = SESSION_CLOSED_BEFORE; it.ErrMsg = SESSION_CLOSED_BEFORE_ERR_MSG; } else { it.ErrMsg = cs.ErrorMsg; } #if TASKS_ENABLED if (it.Fut != null) { it.Fut.TrySetException(new CSocketError(it.ErrCode, it.ErrMsg, idUpload, true)); it.Discarded = null; it.Se = null; } #endif continue; } break; } } else { OpenLocalWrite(it); if (!it.HasError) { if (!SendRequest(idDownload, it.LocalFile, it.FilePath, it.Flags, it.InitSize, rh, it.Discarded, it.Se)) { CClientSocket cs = Socket; it.ErrCode = cs.ErrorCode; if (it.ErrCode == 0) { it.ErrCode = SESSION_CLOSED_BEFORE; it.ErrMsg = SESSION_CLOSED_BEFORE_ERR_MSG; } else { it.ErrMsg = cs.ErrorMsg; } #if TASKS_ENABLED if (it.Fut != null) { it.Fut.TrySetException(new CSocketError(it.ErrCode, it.ErrMsg, idDownload, true)); it.Discarded = null; it.Se = null; } #endif } ++d; } } } while (m_vContext.Count > 0) { CContext it = m_vContext[0]; if (it.HasError) { CloseFile(it); if (it.Uploading) { DUpload cb = it.Upload; if (cb != null) { int errCode = it.ErrCode; string errMsg = it.ErrMsg; try { System.Threading.Monitor.Exit(m_csFile); cb.Invoke(this, errCode, errMsg); } finally { System.Threading.Monitor.Enter(m_csFile); } } } else { DDownload cb = it.Download; if (cb != null) { int errCode = it.ErrCode; string errMsg = it.ErrMsg; try { System.Threading.Monitor.Exit(m_csFile); cb.Invoke(this, errCode, errMsg); } finally { System.Threading.Monitor.Enter(m_csFile); } } } m_vContext.RemoveFromFront(); } else { break; } } System.Threading.Monitor.Exit(m_csFile); }
internal CClientQueueImpl(CClientSocket cs) { m_cs = cs; }
private static bool Mysql_DoSslServerAuthentication(CSocketPool <CMysql> sender, CClientSocket cs) { throw new NotImplementedException(); }
static void Main(string[] args) { Console.WriteLine("Input your user id ......"); CConnectionContext cc = new CConnectionContext("localhost", 20901, Console.ReadLine(), "MyPassword", tagEncryptionMethod.TLSv1); //CA file is located at the directory ..\SocketProRoot\bin CClientSocket.SSL.SetVerifyLocation("ca.cert.pem"); //for windows platforms, you can also use windows system store instead //CClientSocket.SSL.SetVerifyLocation("my"); //or "root", "my@currentuser", "root@localmachine" using (CSocketPool <HelloWorld> spHw = new CSocketPool <HelloWorld>()) //true -- automatic reconnecting { spHw.DoSslServerAuthentication += (sender, cs) => { int errCode; IUcert cert = cs.UCert; Console.WriteLine(cert.SessionInfo); string res = cert.Verify(out errCode); //do ssl server certificate authentication here return(errCode == 0); //true -- user id and password will be sent to server }; //error handling ignored for code clarity bool ok = spHw.StartSocketPool(cc, 1, 1); HelloWorld hw = spHw.Seek(); //or HelloWorld hw = spHw.Lock(); CClientSocket ClientSocket = hw.AttachedClientSocket; ClientSocket.Push.OnSubscribe += (cs, messageSender, groups) => { Console.WriteLine("Subscribe for " + ToString(groups)); Console.WriteLine(ToString(messageSender)); Console.WriteLine(); }; ClientSocket.Push.OnUnsubscribe += (cs, messageSender, groups) => { Console.WriteLine("Unsubscribe from " + ToString(groups)); Console.WriteLine(ToString(messageSender)); Console.WriteLine(); }; ClientSocket.Push.OnPublish += (cs, messageSender, groups, msg) => { Console.WriteLine("Publish to " + ToString(groups)); Console.WriteLine(ToString(messageSender)); Console.WriteLine("message = " + msg); Console.WriteLine(); }; ClientSocket.Push.OnSendUserMessage += (cs, messageSender, msg) => { Console.WriteLine("SendUserMessage"); Console.WriteLine(ToString(messageSender)); Console.WriteLine("message = " + msg); Console.WriteLine(); }; //asynchronously process multiple requests with inline batching for best network efficiency ok = hw.SendRequest(hwConst.idSayHelloHelloWorld, "Jack", "Smith", (ar) => { string ret; ar.Load(out ret); Console.WriteLine(ret); }); uint[] chat_ids = { 1, 2 }; ok = ClientSocket.Push.Publish("We are going to call the method Sleep", chat_ids); CAsyncServiceHandler.DAsyncResultHandler arh = null; ok = hw.SendRequest(hwConst.idSleepHelloWorld, (int)5000, arh); Console.WriteLine("Input a receiver for receiving my message ......"); Console.WriteLine(); ok = ClientSocket.Push.SendUserMessage("A message from " + cc.UserId, Console.ReadLine()); ok = hw.WaitAll(); Console.WriteLine("Press key ENTER to shutdown the demo application ......"); Console.ReadLine(); } }
private void OnSPEvent(uint poolId, tagSocketPoolEvent spe, IntPtr h) { THandler handler = MapToHandler(h); switch (spe) { case tagSocketPoolEvent.speTimer: //Console.WriteLine("Timer running = " + poolId + ", thread id = " + System.Threading.Thread.CurrentThread.ManagedThreadId); break; case tagSocketPoolEvent.speStarted: lock (m_cs) { m_nPoolId = poolId; } break; case tagSocketPoolEvent.speShutdown: lock (m_cs) { m_dicSocketHandler.Clear(); } break; case tagSocketPoolEvent.speUSocketCreated: { CClientSocket cs = new CClientSocket(); cs.Set(h); ClientCoreLoader.SetRecvTimeout(h, m_recvTimeout); ClientCoreLoader.SetConnTimeout(h, m_connTimeout); ClientCoreLoader.SetAutoConn(h, (byte)(m_autoConn ? 1 : 0)); handler = new THandler(); if (handler.SvsID == 0) { handler.m_nServiceId = m_ServiceId; } if (handler.SvsID <= SocketProAdapter.BaseServiceID.sidStartup) { throw new InvalidOperationException("Service id must be larger than SocketProAdapter.BaseServiceID.sidStartup"); } handler.Attach(cs); lock (m_cs) { m_dicSocketHandler[cs] = handler; } } break; case tagSocketPoolEvent.speUSocketKilled: if (handler != null) { lock (m_cs) { m_dicSocketHandler.Remove(handler.AttachedClientSocket); } } break; case tagSocketPoolEvent.speConnecting: break; case tagSocketPoolEvent.speConnected: if (ClientCoreLoader.IsOpened(h) != 0) { CClientSocket cs = handler.AttachedClientSocket; if (DoSslServerAuthentication != null && cs.EncryptionMethod == tagEncryptionMethod.TLSv1 && !DoSslServerAuthentication.Invoke(this, cs)) { return; //don't set password or call SwitchTo in case failure of ssl server authentication on certificate from server } ClientCoreLoader.SetSockOpt(h, tagSocketOption.soRcvBuf, 116800, tagSocketLevel.slSocket); ClientCoreLoader.SetSockOpt(h, tagSocketOption.soSndBuf, 116800, tagSocketLevel.slSocket); ClientCoreLoader.SetSockOpt(h, tagSocketOption.soTcpNoDelay, 1, tagSocketLevel.slTcp); ClientCoreLoader.SetPassword(h, cs.ConnectionContext.GetPassword()); bool ok = ClientCoreLoader.StartBatching(h) != 0; ok = ClientCoreLoader.SwitchTo(h, handler.SvsID) != 0; if (ok) { ok = ClientCoreLoader.TurnOnZipAtSvr(h, (byte)(cs.ConnectionContext.Zip ? 1 : 0)) != 0; ok = ClientCoreLoader.SetSockOptAtSvr(h, tagSocketOption.soRcvBuf, 116800, tagSocketLevel.slSocket) != 0; ok = ClientCoreLoader.SetSockOptAtSvr(h, tagSocketOption.soSndBuf, 116800, tagSocketLevel.slSocket) != 0; ok = ClientCoreLoader.SetSockOptAtSvr(h, tagSocketOption.soTcpNoDelay, 1, tagSocketLevel.slTcp) != 0; } ok = ClientCoreLoader.CommitBatching(h, (byte)0) != 0; } break; case tagSocketPoolEvent.speQueueMergedFrom: m_pHFrom = MapToHandler(h); break; case tagSocketPoolEvent.speQueueMergedTo: { THandler to = MapToHandler(h); m_pHFrom.AppendTo(to); m_pHFrom = null; } break; default: break; } lock (m_cs) { if (SocketPoolEvent != null) { SocketPoolEvent.Invoke(this, spe, handler); } } OnSocketPoolEvent(spe, handler); }
public Form1() { InitializeComponent(); zedview = new ZedGraphView(ref zedGraphControl1); //init zedview.Init(); //Events ---- btnConnect.Click += (o, e) => { txbData.Text = string.Format("Connect to: {0}:{1}", txbAddress.Text, nmPort.Value); soc = new CClientSocket(txbAddress.Text, (int)nmPort.Value); soc.OnConnect += (_soc) => { Invoke((MethodInvoker) delegate { txbData.AppendText(string.Format("Socket {0} is connected", _soc.RemoteEndPoint.ToString())); //btnConnect.Text = "Disconnect"; timer1.Enabled = true; }); }; //soc.OnRead += (_soc) => //{ // Invoke((MethodInvoker)delegate // { // //Format receive: $$,11.1444,6.2323,13.4445,$$ (Hercules - TCP Server) // string strdata = soc.ReceivedText; // //txbData.AppendText(string.Format("Receive {0}:: Data: {1}", _soc.ToString(), strdata)); // txbData.AppendText(strdata + " \r\n"); // string[] subdata = strdata.Split(','); // // // if (subdata[0] == "$") // { // if (subdata.Length >= 3) // { // if (subdata[1] != null) // { // double.TryParse(subdata[1], out volt); //Volt 1 // double.TryParse(subdata[2], out volt1); //Volt 2 // double.TryParse(subdata[3], out volt2); //Volt 3 // zedview.Draw(volt, volt1, volt2); // } // } // } // }); //}; soc.OnDisconnect += (_soc) => { Invoke((MethodInvoker) delegate { txbData.AppendText(string.Format("Disconnect {0}", _soc.ToString())); //btnConnect.Text = "Connect"; }); }; soc.Connect(); }; btnDisconnect.Click += (o, e) => { soc.Disconnect(); }; // btnSend.Click += (o, e) => { soc.SendText(txbSend.Text); }; // btnClear.Click += (o, e) => zedview.Init(); }
protected virtual bool DoSslServerAuthentication(CClientSocket cs) { return(true); }
//----------------------------------------------------------------------------- protected override WvsLoginClient CreateClient(CClientSocket socket) { return(new WvsLoginClient(this, socket)); }
private void OnSPEvent(uint poolId, tagSocketPoolEvent spe, IntPtr h) { THandler handler = MapToHandler(h); switch (spe) { case tagSocketPoolEvent.speTimer: if (CScopeUQueue.MemoryConsumed / 1024 > CScopeUQueue.SHARED_BUFFER_CLEAN_SIZE) { CScopeUQueue.DestroyUQueuePool(); } break; case tagSocketPoolEvent.speStarted: lock (m_cs) { m_nPoolId = poolId; } break; case tagSocketPoolEvent.speShutdown: lock (m_cs) { m_dicSocketHandler.Clear(); } break; case tagSocketPoolEvent.speUSocketCreated: { CClientSocket cs = new CClientSocket(); cs.Set(h); ClientCoreLoader.SetRecvTimeout(h, m_recvTimeout); ClientCoreLoader.SetConnTimeout(h, m_connTimeout); ClientCoreLoader.SetAutoConn(h, (byte)(m_autoConn ? 1 : 0)); handler = new THandler(); if (handler.SvsID == 0) { handler.m_nServiceId = m_ServiceId; } if (handler.SvsID <= SocketProAdapter.BaseServiceID.sidStartup) { throw new InvalidOperationException("Service id must be larger than SocketProAdapter.BaseServiceID.sidStartup"); } handler.Attach(cs); lock (m_cs) { m_dicSocketHandler[cs] = handler; } } break; case tagSocketPoolEvent.speUSocketKilled: if (handler != null) { lock (m_cs) { m_dicSocketHandler.Remove(handler.AttachedClientSocket); } } break; case tagSocketPoolEvent.speConnecting: break; case tagSocketPoolEvent.speConnected: if (ClientCoreLoader.IsOpened(h) != 0) { CClientSocket cs = handler.AttachedClientSocket; if (DoSslServerAuthentication != null && cs.EncryptionMethod == tagEncryptionMethod.TLSv1 && !DoSslServerAuthentication.Invoke(this, cs)) { return; //don't set password or call SwitchTo in case failure of ssl server authentication on certificate from server } ClientCoreLoader.SetSockOpt(h, tagSocketOption.soRcvBuf, 116800, tagSocketLevel.slSocket); ClientCoreLoader.SetSockOpt(h, tagSocketOption.soSndBuf, 116800, tagSocketLevel.slSocket); ClientCoreLoader.SetSockOpt(h, tagSocketOption.soTcpNoDelay, 1, tagSocketLevel.slTcp); ClientCoreLoader.SetPassword(h, cs.ConnectionContext.GetPassword()); bool ok = ClientCoreLoader.StartBatching(h) != 0; ok = ClientCoreLoader.SwitchTo(h, handler.SvsID) != 0; ok = ClientCoreLoader.TurnOnZipAtSvr(h, (byte)(cs.ConnectionContext.Zip ? 1 : 0)) != 0; ok = ClientCoreLoader.SetSockOptAtSvr(h, tagSocketOption.soRcvBuf, 116800, tagSocketLevel.slSocket) != 0; ok = ClientCoreLoader.SetSockOptAtSvr(h, tagSocketOption.soSndBuf, 116800, tagSocketLevel.slSocket) != 0; ok = ClientCoreLoader.SetSockOptAtSvr(h, tagSocketOption.soTcpNoDelay, 1, tagSocketLevel.slTcp) != 0; ok = (ClientCoreLoader.CommitBatching(h, (byte)0) != 0); } break; case tagSocketPoolEvent.speQueueMergedFrom: m_pHFrom = MapToHandler(h); #if DEBUG IClientQueue cq = m_pHFrom.AttachedClientSocket.ClientQueue; uint remaining = (uint)m_pHFrom.RequestsQueued; if (cq.MessageCount != remaining) { Console.WriteLine("From: Messages = {0}, remaining requests = {1}", cq.MessageCount, remaining); } #endif break; case tagSocketPoolEvent.speQueueMergedTo: { THandler to = MapToHandler(h); m_pHFrom.AppendTo(to); m_pHFrom = null; } break; default: break; } if (SocketPoolEvent != null) { SocketPoolEvent.Invoke(this, spe, handler); } OnSocketPoolEvent(spe, handler); if (spe == tagSocketPoolEvent.speConnected && ClientCoreLoader.IsOpened(h) != 0) { SetQueue(handler.AttachedClientSocket); } }
protected override void Initialize() { CClientSocket.SetAesKey(Constants.Userkey); m_stage = new LoginStage(); Player = new CUserLocal(); Socket = new CClientSocket(this); base.Initialize(); }
private void Push_OnPublish(CClientSocket sender, CMessageSender messageSender, uint[] group, object msg) { //this event is fired from worker thread from socket pool thread string message = "", filter = ""; List <KeyValuePair <DataColumn, object> > vKeyVal = new List <KeyValuePair <DataColumn, object> >(); object[] vData = (object[])msg; //vData[0] == event type; vData[1] == host; vData[2] = user; vData[3] == db name; vData[4] == table name tagUpdateEvent ue = (tagUpdateEvent)(int)vData[0]; string table_name = vData[3].ToString() + "." + vData[4].ToString(); lock (m_cs) { DataTable dt = m_ds.Tables[table_name]; if (dt == null) { return; } DataColumn[] keys = dt.PrimaryKey; int cols = dt.Columns.Count; switch (ue) { case tagUpdateEvent.ueUpdate: { foreach (DataColumn dc in keys) { KeyValuePair <DataColumn, object> kv = new KeyValuePair <DataColumn, object>(dc, vData[5 + 2 * dc.Ordinal]); vKeyVal.Add(kv); } DataRow dr = FindRowByKeys(dt, vKeyVal, ue, out filter); for (int n = 0; n < cols; ++n) { if (dt.Columns[n].ReadOnly) { continue; } object d = vData[5 + 2 * n + 1]; dr[n] = d; } message = "Table " + table_name + " updated for row (" + filter + ")"; } break; case tagUpdateEvent.ueDelete: { int index = 0; foreach (DataColumn dc in keys) { KeyValuePair <DataColumn, object> kv = new KeyValuePair <DataColumn, object>(dc, vData[5 + index]); vKeyVal.Add(kv); ++index; } dt.Rows.Remove(FindRowByKeys(dt, vKeyVal, ue, out filter)); message = "Table " + table_name + " deleted for row (" + filter + ")"; } break; case tagUpdateEvent.ueInsert: { foreach (DataColumn dc in keys) { KeyValuePair <DataColumn, object> kv = new KeyValuePair <DataColumn, object>(dc, vData[5 + dc.Ordinal]); vKeyVal.Add(kv); } DataRow dr = FindRowByKeys(dt, vKeyVal, ue, out filter); //generate filter only dr = dt.NewRow(); for (int n = 0; n < cols; ++n) { dr[n] = vData[5 + n]; } dt.Rows.Add(dr); message = "Table " + table_name + " inserted for row (" + filter + ")"; } break; default: message = "Unknown DB message found"; //shouldn't come here break; } BeginInvoke(m_thread_message, message, dt); } }
protected override void OnResultReturned(ushort reqId, CUQueue mc) { switch (reqId) { case idDownload: { int res; string errMsg; mc.Load(out res).Load(out errMsg); DDownload dl = null; lock (m_csFile) { if (m_vContext.Count > 0) { CContext ctx = m_vContext[0]; ctx.ErrCode = res; ctx.ErrMsg = errMsg; dl = ctx.Download; } } if (dl != null) { dl.Invoke(this, res, errMsg); } lock (m_csFile) { if (m_vContext.Count > 0) { CloseFile(m_vContext.RemoveFromFront()); } } OnPostProcessing(0, 0); } break; case idStartDownloading: lock (m_csFile) { long fileSize; string localFile, remoteFile; uint flags; long initSize; mc.Load(out fileSize).Load(out localFile).Load(out remoteFile).Load(out flags).Load(out initSize); lock (m_csFile) { if (m_vContext.Count == 0) { CContext ctx = new CContext(false, flags); ctx.LocalFile = localFile; ctx.FilePath = remoteFile; OpenLocalWrite(ctx); ctx.InitSize = initSize; m_vContext.AddToBack(ctx); } CContext context = m_vContext[0]; context.FileSize = fileSize; initSize = (context.InitSize > 0) ? context.InitSize : 0; if (context.File.Position > initSize) { context.File.SetLength(initSize); } } } break; case idDownloading: { long downloaded = 0; DTransferring trans = null; CContext context = null; lock (m_csFile) { if (m_vContext.Count > 0) { context = m_vContext[0]; trans = context.Transferring; byte[] buffer = mc.IntenalBuffer; try { context.File.Write(buffer, 0, (int)mc.GetSize()); long initSize = (context.InitSize > 0) ? context.InitSize : 0; downloaded = context.File.Position - initSize; } catch (System.IO.IOException err) { context.ErrMsg = err.Message; #if NO_HRESULT context.ErrCode = CANNOT_OPEN_LOCAL_FILE_FOR_WRITING; #else context.ErrCode = err.HResult; #endif } } } mc.SetSize(0); if (context != null && context.HasError) { if (context.Download != null) { context.Download.Invoke(this, context.ErrCode, context.ErrMsg); } CloseFile(m_vContext.RemoveFromFront()); OnPostProcessing(0, 0); } else if (trans != null) { trans.Invoke(this, downloaded); } } break; case idUploadBackup: break; case idUpload: { CContext context = null; int res; string errMsg; mc.Load(out res).Load(out errMsg); if (res != 0 || (errMsg != null && errMsg.Length > 0)) { lock (m_csFile) { if (m_vContext.Count > 0) { context = m_vContext[0]; mc.Load(out context.InitSize); context.ErrCode = res; context.ErrMsg = errMsg; } } } else { CClientSocket cs = Socket; lock (m_csFile) { if (m_vContext.Count > 0) { context = m_vContext[0]; mc.Load(out context.InitSize); using (CScopeUQueue sb = new CScopeUQueue()) { DAsyncResultHandler rh = null; DOnExceptionFromServer se = null; if (sb.UQueue.MaxBufferSize < STREAM_CHUNK_SIZE) { sb.UQueue.Realloc(STREAM_CHUNK_SIZE); } byte[] buffer = sb.UQueue.IntenalBuffer; try { context.QueueOk = cs.ClientQueue.StartJob(); bool queue_enabled = cs.ClientQueue.Available; if (queue_enabled) { SendRequest(idUploadBackup, context.FilePath, context.Flags, context.FileSize, context.InitSize, rh, context.Discarded, se); } int ret = context.File.Read(buffer, 0, (int)STREAM_CHUNK_SIZE); while (ret == STREAM_CHUNK_SIZE) { if (!SendRequest(idUploading, buffer, (uint)ret, rh, context.Discarded, se)) { context.ErrCode = cs.ErrorCode; context.ErrMsg = cs.ErrorMsg; break; } ret = context.File.Read(buffer, 0, (int)STREAM_CHUNK_SIZE); if (queue_enabled) { //save file into client message queue } else if (cs.BytesInSendingBuffer > 40 * STREAM_CHUNK_SIZE) { break; } } if (ret > 0 && !context.HasError) { if (!SendRequest(idUploading, buffer, (uint)ret, rh, context.Discarded, se)) { context.ErrCode = cs.ErrorCode; context.ErrMsg = cs.ErrorMsg; } } if (ret < STREAM_CHUNK_SIZE && !context.HasError) { context.Sent = true; SendRequest(idUploadCompleted, rh, context.Discarded, se); if (context.QueueOk) { Socket.ClientQueue.EndJob(); } } } catch (System.IO.IOException err) { errMsg = err.Message; #if NO_HRESULT res = CANNOT_OPEN_LOCAL_FILE_FOR_READING; #else res = err.HResult; #endif context.ErrCode = res; context.ErrMsg = errMsg; } } } } } if (context != null && context.HasError) { if (context.Upload != null) { context.Upload.Invoke(this, context.ErrCode, context.ErrMsg); } lock (m_csFile) { CloseFile(m_vContext.RemoveFromFront()); } if (context.QueueOk) { Socket.ClientQueue.AbortJob(); } OnPostProcessing(0, 0); } } break; case idUploading: { int errCode = 0; string errMsg = ""; CContext context = null; DTransferring trans = null; long uploaded; mc.Load(out uploaded); if (mc.GetSize() >= 8) { mc.Load(out errCode).Load(out errMsg); } lock (m_csFile) { if (m_vContext.Count > 0) { context = m_vContext[0]; trans = context.Transferring; if (uploaded < 0 || errCode != 0 || errMsg.Length != 0) { context.ErrCode = errCode; context.ErrMsg = errMsg; CloseFile(context); } else if (!context.Sent) { using (CScopeUQueue sb = new CScopeUQueue()) { DAsyncResultHandler rh = null; DOnExceptionFromServer se = null; if (sb.UQueue.MaxBufferSize < STREAM_CHUNK_SIZE) { sb.UQueue.Realloc(STREAM_CHUNK_SIZE); } byte[] buffer = sb.UQueue.IntenalBuffer; try { int ret = context.File.Read(buffer, 0, (int)STREAM_CHUNK_SIZE); if (ret > 0) { SendRequest(idUploading, buffer, (uint)ret, rh, context.Discarded, se); } if (ret < STREAM_CHUNK_SIZE) { context.Sent = true; SendRequest(idUploadCompleted, rh, context.Discarded, se); } } catch (System.IO.IOException err) { context.ErrMsg = err.Message; #if NO_HRESULT context.ErrCode = CANNOT_OPEN_LOCAL_FILE_FOR_READING; #else context.ErrCode = err.HResult; #endif } } } } } if (context != null && context.HasError) { if (context.Upload != null) { context.Upload.Invoke(this, context.ErrCode, context.ErrMsg); } lock (m_csFile) { CloseFile(m_vContext.RemoveFromFront()); } OnPostProcessing(0, 0); } else if (trans != null) { trans.Invoke(this, uploaded); } } break; case idUploadCompleted: { DUpload upl = null; lock (m_csFile) { if (m_vContext.Count > 0) { if (m_vContext[0].File != null) { upl = m_vContext[0].Upload; } else { m_vContext[0].QueueOk = false; m_vContext[0].Sent = false; CloseFile(m_vContext[0]); } } } if (upl != null) { upl.Invoke(this, 0, ""); } lock (m_csFile) { if (m_vContext.Count > 0) { if (m_vContext[0].File != null) { CloseFile(m_vContext.RemoveFromFront()); } } } OnPostProcessing(0, 0); } break; default: base.OnResultReturned(reqId, mc); break; } }