private clientInfo getClientInfo(string id) { string connectionString = ConfigurationManager.ConnectionStrings["KioskConnectionString"].ConnectionString; using (SqlConnection con = new SqlConnection(connectionString)) using (SqlCommand cmd = new SqlCommand("SELECT kiosk_id, region FROM kiosk WHERE id=@id", con)) { cmd.Parameters.AddWithValue("id", id); con.Open(); SqlDataReader rdr = cmd.ExecuteReader(); if (rdr.HasRows) { clientInfo client = null; while (rdr.Read()) { client = new clientInfo { region = rdr["region"].ToString(), ID = rdr["kiosk_id"].ToString() }; } con.Close(); return(client); } else { con.Close(); return(null); } } }
// client public ChatForm(Connection newTCPConn) { NetworkComms.AppendGlobalIncomingPacketHandler <messageHolder>("Message", addMessage); NetworkComms.AppendGlobalIncomingPacketHandler <clientInfo>("ClientInfo", c_addClient); clientList = new ArrayList(); this.newTCPConn = newTCPConn; InitializeComponent(); isHost = false; cinfo = new clientInfo("Anonymous"); try { newTCPConn.SendObject("ClientInfo", cinfo); } catch (Exception e) { MessageBox.Show("ERR: " + e.Message); return; } String msg = "Connection successful."; ChatLog.Items.Add(msg); Users.Items.Add(cinfo.name); Rank.Items.Add("G"); }
/// <summary> /// 获取客户端 /// </summary> /// <param name="identity"></param> /// <returns></returns> private clientInfo getClient(indexIdentity identity) { if (clientPool.Enter()) { clientInfo client = clientPool.Pool[identity.Index].Get(identity.Identity); clientPool.Exit(); return(client); } return(null); }
/// <summary> /// 释放客户端索引编号 /// </summary> /// <param name="identity"></param> /// <returns></returns> public bool Free(int identity) { if (identity == Identity) { Client = null; ++Identity; return(true); } return(false); }
private static string SetNameProc(clientInfo user, string args) { if (args.Trim().Length == 0) { user.UserName = ((IPEndPoint)user.Client.Client.RemoteEndPoint).Address.ToString() + ":" + ((IPEndPoint)user.Client.Client.RemoteEndPoint).Port.ToString(); } else { user.UserName = args; } return("NEWNAME:" + user.UserName); }
private void addClient(PacketHeader packetHeader, Connection connection, clientInfo incomingObject) { clientInfoServ toAdd = new clientInfoServ(incomingObject.name, connection); //MessageBox.Show("Name: " + incomingObject.name); addUser(toAdd); try { TCPConnection.GetConnection(connection.ConnectionInfo).SendObject("ClientInfo", chost); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// TCP服务端轮询 /// </summary> /// <param name="clientId">TCP服务端标识</param> /// <param name="logIdentity">日志编号</param> /// <param name="onLog">TCP服务注册通知委托</param> internal void GetLog(ref clientId clientId, int logIdentity, Func <fastCSharp.net.returnValue <log>, bool> onLog) { clientInfo client = getClient(ref clientId); if (client != null) { onLog = Interlocked.Exchange(ref client.OnLog, onLog); if (onLog == null) { logStream.Get(logIdentity, client.OnLogHandle); } else { onLog(log.NewGetter); } return; } onLog(log.ClientError); }
/// <summary> /// TCP服务端注册 /// </summary> /// <returns>TCP服务端标识</returns> internal clientId Register() { clientInfo clientInfo = new clientInfo(); indexIdentity identity; if (clientPool.Enter()) { try { identity.Index = clientPool.GetIndexContinue();//不能写成一行,可能造成Pool先入栈然后被修改,导致索引溢出 identity.Identity = clientPool.Pool[identity.Index].Set(clientInfo); } finally { clientPool.Exit(); } return(new clientId { Tick = logStream.Ticks, Identity = identity }); } clientPool.Exit(); return(default(clientId)); }
public static bool CheckServerCommands(clientInfo user, string message, out string reply) { reply = String.Empty; string[] commands = message.Split(':'); if (commands.Length < 2) { return(false); } else { ServerCommandProc proc; cmdDict.TryGetValue(commands[0], out proc); if (proc != null) { reply = proc.Invoke(user, commands[1]); return(true); } return(false); } }
private void c_addClient(PacketHeader packetHeader, Connection connection, clientInfo incomingObject) { foreach (clientInfoServ cinfo in clientList) { Connection conn = cinfo.conn; if (connection == null || connection.Equals(conn)) { continue; } connection.SendObject("Message", incomingObject); } Rank.Invoke(new MethodInvoker(delegate() { Rank.Items.Add(incomingObject.rank); })); Users.Invoke(new MethodInvoker(delegate() { Users.Items.Add(incomingObject.name); })); }
protected void Page_Load(object sender, EventArgs e) { string id = Request.QueryString["id"]; clientInfo client = new clientInfo(); if (!String.IsNullOrEmpty(id)) { client = getClientInfo(id); } else { client.region = ""; } if (client.region == "") { main.InnerHtml = "<p id=\"registration-container\">It appears that this machine is not registered. Would you like to add it to the database?<br /><br /><input type=\"submit\" value=\"Register\" id=\"registration\" /></p>"; } else { tag.InnerHtml = "<span id=\"tag-info\">" + client.region.ToUpper() + " " + client.ID + "</span>"; } }
//server public ChatForm(int port) { clientList = new ArrayList(); InitializeComponent(); this.port = port; this.ip = "192.168.1.123"; isHost = true; // [ttaj] Setup the server, if the object being sent is a string then run the function PrintIncMsg NetworkComms.AppendGlobalIncomingPacketHandler <clientInfo>("ClientInfo", addClient); NetworkComms.AppendGlobalIncomingPacketHandler <messageHolder>("Message", addMessage); // [ttaj] Start the server. TCPConnection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(IPAddress.Parse(ip), port)); host = new clientInfoServ("Host", null, "H"); chost = new clientInfo("Host", "H"); ChatLog.Items.Add("Server successfully started!"); clientList.Add(host); Users.Items.Add(host.name); Rank.Items.Add(host.rank); }
/// <summary> /// /// </summary> /// <param name="clientApyKey"></param> //public void ThreadNotification(string clientApiKey, string clientDateFromtoSearch) { public void ThreadNotification(clientInfo oClient) { StateObjClass StateObj = new StateObjClass(); StateObj.TimerCanceled = false; StateObj.clientApiKey = oClient.clientApyKey; //clientApiKey; StateObj.searchfromDate = oClient.creationDate; //clientDateFromtoSearch; StateObj.clientId = oClient.idUser; System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(listNotificationsThread); oThreadNotification = new Timer(TimerDelegate, StateObj, 0, Convert.ToInt32(ConfigurationSettings.AppSettings["timer"])); }
public void addClientInfo(clientInfo u) { new ClientInfoRepository().addClientInfo(u); }
/// <summary> /// /// </summary> /// <param name="idUser"></param> /// <param name="clientApyKey"></param> public void registerClient(string idUser, string clientApiKey, int pageIndex = 1, int pageSize = 10) { lock (oClients) { bool existClient = oClients.FindAll(clientInfo => clientInfo.idUser == idUser).Count > 0; clientInfo oClient = new clientInfo(); if (!existClient) { oClient.idUser = idUser; oClient.clientCaller = Clients.Caller; oClient.clientApyKey = clientApiKey; //oClient.creationDate = DateTime.Now.AddSeconds(10).ToString("yyyyMMdd HH:mm:ss"); oClient.creationDate = DateTime.Now.AddSeconds(10).ToString("yyyyMMdd HH:mm:ss"); oClients.Add(oClient); } else { oClient = oClients.FindAll(clientInfo => clientInfo.idUser == idUser)[0]; //oClient.creationDate = DateTime.Now.ToString("dd/MM/YYYY"); oClients.FindAll(clientInfo => clientInfo.idUser == idUser)[0].creationDate = DateTime.Now.AddSeconds(10).ToString("yyyyMMdd HH:mm:ss"); } listNotifications(clientApiKey, pageIndex, pageSize); //ThreadNotification(oClient.clientApyKey, oClient.creationDate); ThreadNotification(oClient); } }
// This the call back function which will be invoked when the socket // detects any client writing of data on the stream public void OnDataReceived(IAsyncResult asyn) { try { SocketPacket socketData = (SocketPacket)asyn.AsyncState; int iRx = 0; // Complete the BeginReceive() asynchronous call by EndReceive() method // which will return the number of characters written to the stream // by the client iRx = socketData.m_currentSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.Default.GetDecoder(); int charLen = d.GetChars(socketData.dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); string incoming = szData.Substring(0, szData.Length - 1); if (incoming.StartsWith("/rsaC")) { #if _SHOWMSG MessageBox.Show("RSA public key received"); #endif string rsaKey = incoming.Substring(5); string[] fields = rsaKey.Split(' '); clientInfo tempclient = new clientInfo(); tempclient.ip = fields[0]; tempclient.port = fields[1]; tempclient.publicKey = fields[2]; if(!clientsList.Contains(tempclient)) clientsList.Add(tempclient); } else if (incoming.StartsWith("/bck")) { //client wants to back up //decide which parties to connect //pseudo connections list. string[] backupreq = incoming.Substring(4).Split(' '); //client req = new client(); int clientnum = -1; for (int i = 0; i < clientsList.Count; i++) { if (clientsList[i].ip.Equals(backupreq[0])) { if (clientsList[i].port.Equals(backupreq[1])) { clientnum = i; } } } if (clientnum == -1) MessageBox.Show("Backup Request from unauthenticated user"); else { //req = clientsList[clientnum]; clientsList[clientnum].files[0].fileID = backupreq[2]; clientsList[clientnum].files[0].filesize = System.Convert.ToInt32(backupreq[3]); //first part of every ticket is same string ticketData = clientsList[clientnum].ip + " " + clientsList[clientnum].port + " " + clientsList[clientnum].publicKey; // Create a UnicodeEncoder to convert between byte array and string. ASCIIEncoding ByteConverter = new ASCIIEncoding(); byte[] originalData = ByteConverter.GetBytes(ticketData); byte[] signedData; signedData = rsa.SignData(originalData, new SHA1CryptoServiceProvider()); for (int i = 0; i < clientsList.Count; i++) { //Ticket i = E(PRas, IPa + PUa) || E(PRas, IPb + PUb) if (i != clientnum) { //second part of the ticket string ticketSecondData = clientsList[i].ip + " " + clientsList[i].port + " " + clientsList[i].publicKey; // Create a UnicodeEncoder to convert between byte array and string. byte[] originalSecondData = ByteConverter.GetBytes(ticketSecondData); byte[] signedSecondData; signedSecondData = rsa.SignData(originalSecondData, new SHA1CryptoServiceProvider()); clientsList[clientnum].files[0].filetickets.AddToList(originalData, signedData, originalSecondData, signedSecondData); } } //sends them to the client try { string functionID = "/tck"; string strTickets = clientsList[clientnum].files[0].filetickets.EncodeToString(); //TODO: somehow concatanate the message header; functionID string TicketListMsg = functionID + strTickets; //tickets byte[] byData2 = System.Text.Encoding.ASCII.GetBytes(TicketListMsg); if (m_workerSocket[clientnum] != null) { if (m_workerSocket[clientnum].Connected) { m_workerSocket[clientnum].Send(byData2); } } } catch (SocketException se) { MessageBox.Show(se.Message); } } //mytickets tickets = new mytickets(); //clients[] clientsList = new clients[5]; //for (int i = 0; i < 5; i++) //{ // clientsList[i].ip = i * 100; // clientsList[i].port = i * 1000; // clientsList[i].publicKey = (i * 10000).ToString(); //} } else if (incoming.StartsWith("/rcv")) { //client wants to recover //decide which parties to connect //pseudo connections list. string[] recoverreq = incoming.Substring(4).Split(' '); //client req = new client(); int clientnum = -1; int filenum = -1; for (int i = 0; i < clientsList.Count; i++) { if (clientsList[i].ip.Equals(recoverreq[0])) { if (clientsList[i].port.Equals(recoverreq[1])) { for (int j = 0; j < MAX_FILE; j++) { if (clientsList[i].files[j].fileID != null) { if (clientsList[i].files[j].fileID.Equals(recoverreq[2])) { clientnum = i; filenum = j; break; } } } } } } if (clientnum == -1) MessageBox.Show("User nor authenticated!"); else if (filenum == -1) MessageBox.Show("File not in database!"); else { //req = clientsList[clientnum]; mytickets RecoveryTickets = new mytickets(); bool enoughFound = false; for (int i = 0; !enoughFound && i < clientsList[clientnum].files[filenum].filetickets.ticketlist.Count; i++) { string possibleStorage = new ASCIIEncoding().GetString(clientsList[clientnum].files[filenum].filetickets.ticketlist[i].origSecond); string[] fields = possibleStorage.Split(' '); string possibleStorageIP = fields[0]; string possibleStoragePort = fields[1]; for (int j = 0; j < m_clientCount; j++) { if (m_workerSocket[j] != null) { if (m_workerSocket[j].Connected) { if (possibleStorageIP.Equals(clientsList[j].ip)) { if (possibleStoragePort.Equals(clientsList[j].port)) { RecoveryTickets.AddToList(clientsList[clientnum].files[filenum].filetickets.ticketlist[i]); if (RecoveryTickets.ticketlist.Count >= clientsList[clientnum].files[filenum].filetickets.ticketlist.Count - 1) enoughFound = true; } } } } } } //sends them to the client try { string functionID = "/rectck"; string strTickets = RecoveryTickets.EncodeToString(); //TODO: somehow concatanate the message header; functionID string TicketListMsg = functionID + strTickets; //tickets byte[] byData2 = System.Text.Encoding.ASCII.GetBytes(TicketListMsg); if (m_workerSocket[clientnum] != null) { if (m_workerSocket[clientnum].Connected) { m_workerSocket[clientnum].Send(byData2); } } } catch (SocketException se) { MessageBox.Show(se.Message); } } } else { tb_encRecv.Enabled = true; tb_encRecv.Text = BytesToHex(Convert.FromBase64String(szData.Substring(0, szData.Length - 1))); string decryptedText = cryptor.DecryptMessage(szData.Substring(0, szData.Length - 1)); richTextBoxReceivedMsg.Text = decryptedText + "\n" + richTextBoxReceivedMsg.Text; } // Continue the waiting for data on the Socket WaitForData(socketData.m_currentSocket); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { MessageBox.Show(se.Message); } }
/// <summary> /// 注册TCP服务信息 /// </summary> /// <param name="identity">TCP服务端标识</param> /// <param name="service">TCP服务信息</param> /// <param name="services">TCP服务信息集合</param> /// <param name="serviceName">TCP服务名称标识</param> /// <returns>注册状态</returns> private registerResult register(indexIdentity identity, service service, services services, ref hashString serviceName) { int hostCount = 0; if (services.IsSingle || service.IsSingle) { foreach (host host in services.Hosts) { indexIdentity oldClientIdentity; if (hostClients.TryGetValue(host, out oldClientIdentity)) { clientInfo oldClient = getClient(oldClientIdentity); if (oldClient != null && oldClient.OnLog != null && oldClient.OnLog(log.Check)) { services.Hosts[hostCount++] = host; } else { hostClients.Remove(host); } } } if (hostCount != 0) { if (hostCount != services.Hosts.Length) { Array.Resize(ref services.Hosts, hostCount); appendLog(new log { Type = log.type.HostChanged, Services = new services { Name = service.Name, Hosts = services.Hosts.copy() } }); } if (service.IsPerp) { getPort(identity, ref service.Host, true); if (service.Host.Port == 0) { return new registerResult { State = registerState.PortError } } ; services.SetPerpService(identity, service); return(new registerResult { State = registerState.Success, Service = service }); } return(new registerResult { State = registerState.SingleError }); } services.IsSingle = false; services.Hosts = nullValue <host> .Array; getPort(identity, ref service.Host, true); if (service.Host.Port == 0 || (service.IsCheck && hostClients.ContainsKey(service.Host))) { serviceCache.Remove(serviceName); appendLog(new log { Type = log.type.RemoveServiceName, Services = new services { Name = service.Name } }); return(new registerResult { State = service.Host.Port == 0 ? registerState.PortError : registerState.HostExists }); } hostClients[service.Host] = identity; services.Hosts = new host[] { service.Host }; services.IsSingle = service.IsSingle; appendLog(new log { Type = log.type.HostChanged, Services = new services { Name = service.Name, Hosts = new host[] { service.Host } } }); } else { getPort(identity, ref service.Host, true); if (service.Host.Port == 0) { return new registerResult { State = registerState.PortError } } ; if (service.IsCheck && hostClients.ContainsKey(service.Host)) { return new registerResult { State = registerState.HostExists } } ; hostClients[service.Host] = identity; host[] hosts = new host[services.Hosts.Length + 1]; Array.Copy(services.Hosts, 0, hosts, 1, services.Hosts.Length); hosts[0] = service.Host; services.Hosts = hosts; appendLog(new log { Type = log.type.HostChanged, Services = new services { Name = service.Name, Hosts = services.Hosts.copy() } }); } return(new registerResult { State = registerState.Success, Service = service }); }
/// <summary> /// 设置客户端信息 /// </summary> /// <param name="client"></param> /// <returns></returns> public int Set(clientInfo client) { Client = client; return(Identity); }
public void updateClientInfo(clientInfo u) { new ClientInfoRepository().updateclientInfo(u); }