private void SendServerMessage(ClientNode cn, ServerSend sCmd) { string cmd = sCmd.ToString(); //testing cn._Tx = Encoding.ASCII.GetBytes(sCmd.ToString()); cn._Client.GetStream().BeginWrite(cn._Tx, 0, cn._Tx.Length, OnCompleteWriteTcpClient, cn._Client); }
//функция принятия входящих подключений void onCompleteAcceptTcpClient(IAsyncResult iar) { TcpListener tcpl = (TcpListener)iar.AsyncState; //получаем слушателя, который обрабатывает запрос клиента TcpClient tclient = null; ClientNode cNode = null; //используется для работы с клиентами try { tclient = tcpl.EndAcceptTcpClient(iar);//принятие входящей попытки подлючения printLine("Client Connected..."); tcpl.BeginAcceptTcpClient(onCompleteAcceptTcpClient, tcpl); lock (mlClientSocks) { mlClientSocks.Add((cNode = new ClientNode(tclient, new byte[100000], new byte[100000], tclient.Client.RemoteEndPoint.ToString()))); //создание нового клиента lbClients.Items.Add(cNode.ToString()); //добавление нового клиента в список всех клиентов } tclient.GetStream().BeginRead(cNode.Rx, 0, cNode.Rx.Length, onCompleteReadFromTCPClientStream, tclient);//начинаем чтения данных с клиентов //mRx = new byte[512]; //mTCPClient.GetStream().BeginRead(mRx, 0, mRx.Length, onCompleteReadFromTCPClientStream, mTCPClient); } catch (Exception exc) { MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void OnCompleteAcceptTcpClient(IAsyncResult iar) { TcpListener listener = (TcpListener)iar.AsyncState; TcpClient client = null; ClientNode cn = new ClientNode(); try { client = listener.EndAcceptTcpClient(iar); listener.BeginAcceptTcpClient(OnCompleteAcceptTcpClient, listener); lock (_clientSocks) { //string ipAddr = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString(); _clientSocks.Add((cn = new ClientNode(client, new byte[cn.BufSize], new byte[cn.BufSize], client.Client.RemoteEndPoint.ToString()))); //lbClients.Items.Add(cn.ToString()); } PrintLine(cn, "Client connected"); client.GetStream().BeginRead(cn._Rx, 0, cn._Rx.Length, OnCompleteReadTcpClient, client); SendServerClientID(cn); //_buffer = new byte[_bufLen]; //_tcpClient.GetStream().BeginRead(_buffer, 0, _buffer.Length, OnCompleteReadTcpClient, _tcpClient); } catch (Exception ex) { ExceptionMessageHandler(cn, ex); } }
void onCompleteAcceptTcpClient(IAsyncResult iar) { TcpListener tcpl = (TcpListener)iar.AsyncState; TcpClient tclient = null; ClientNode cNode = null; try { tclient = tcpl.EndAcceptTcpClient(iar); printLine("Client Connected..."); tcpl.BeginAcceptTcpClient(onCompleteAcceptTcpClient, tcpl); lock (mlClientSocks) { mlClientSocks.Add((cNode = new ClientNode(tclient, new byte[512], new byte[512], tclient.Client.RemoteEndPoint.ToString()))); lbClients.Items.Add(cNode.ToString()); } tclient.GetStream().BeginRead(cNode.Rx, 0, cNode.Rx.Length, onCompleteReadFromTCPClientStream, tclient); //mRx = new byte[512]; //mTCPClient.GetStream().BeginRead(mRx, 0, mRx.Length, onCompleteReadFromTCPClientStream, mTCPClient); } catch (Exception exc) { MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void SendData([Optional] byte[] RequestedBytes, [Optional] ClientNode RequestedClient) { if (lbClients.Items.Count <= 0) { return; } //if (string.IsNullOrEmpty(tbPayload.Text)) return; ClientNode cn = RequestedClient; lock (mlClientSocks) { try { if (cn == null) { cn = mlClientSocks.Find(x => x.strId == lbClients.SelectedItem.ToString()); } else { cn = RequestedClient; } cn.Tx = new byte[200000]; } catch (Exception exc) { MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } try { if (cn != null) { if (cn.tclient != null) { if (cn.tclient.Client.Connected) { //Image mImage = Image.FromFile("C:\\Users\\karim\\Desktop\\Picture.jpg"); //cn.Tx = ImageToByte(mImage); cn.Tx = RequestedBytes; //cn.Tx = Encoding.ASCII.GetBytes(tbPayload.Text); //cn.Tx = RequestedBytes; cn.tclient.GetStream().BeginWrite(cn.Tx, 0, cn.Tx.Length, onCompleteWriteToClientStream, cn.tclient); } } } } catch (Exception exc) { MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private void SendServerClientNames(ClientNode cn) { for (int i = 0; i < lbClients.Items.Count; i++) { string scid = lbClients.Items[i].ToString(); if (scid != cn.FullId) { SendServerMessage(cn, new ServerSend(OperationType.ServerClientName, scid)); } } }
private void button2_Click(object sender, EventArgs e) { try { if (lbClients.Items.Count <= 0) { return; } ClientNode cn = null; cn = mlClientSocks.Find(x => x.strId == lbClients.SelectedItem.ToString()); //выбор определённого клиента для отправки сообщения cn.Tx = new byte[Convert.ToInt32(textBox2.Text)]; //буффер для отправки int k = 0; while (k < Convert.ToInt32(textBox3.Text)) { lock (mlClientSocks)//lock используется для того,чтобы синхронизировать потоки и ограничить доступ к разделяемым ресурсам на время их использования каким-нибудь потоком. { try { if (cn != null) { if (cn.tclient != null) { if (cn.tclient.Client.Connected) { string message = ""; for (int i = 0; i < Convert.ToInt32(textBox2.Text); i++) { message += "q"; } cn.Tx = Encoding.UTF8.GetBytes(message); //преобразование Text в byte cn.tclient.GetStream().BeginWrite(cn.Tx, 0, cn.Tx.Length, onCompleteWriteToClientStream, cn.tclient); //отправка сообщения клиенту //System.Threading.Thread.Sleep(100); // MessageBox.Show("Сообщение отправлено!"); } } } } catch (Exception exc) { MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } k++; } //tbPayload.Text = ""; } } catch (Exception p) { MessageBox.Show("Выберите получателя для отправки сообщения"); } }
public void PrintLine(ClientNode cn, string str) { string entry; if (cn == null) { entry = str; } else { entry = String.Format("|{0}| {1}", string.IsNullOrEmpty(cn.Name) ? cn._Id : cn.Name, str); } tbConsoleOutput.Invoke(new Action <string>(DoInvoke), entry); }
void onCompleteReadFromTCPClientStream(IAsyncResult iar) { TcpClient tcpc; int nCountReadBytes = 0; string strRecv; ClientNode cn = null; try { lock (mlClientSocks) { tcpc = (TcpClient)iar.AsyncState; cn = mlClientSocks.Find(x => x.strId == tcpc.Client.RemoteEndPoint.ToString()); nCountReadBytes = tcpc.GetStream().EndRead(iar); if (nCountReadBytes == 0)// this happens when the client is disconnected { MessageBox.Show("Client disconnected."); mlClientSocks.Remove(cn); lbClients.Items.Remove(cn.ToString()); return; } string hex = BitConverter.ToString(cn.Rx); hex.Replace("-", ""); // strRecv = Encoding.ASCII.GetString(cn.Rx, 0, nCountReadBytes).Trim(); //strRecv = Encoding.ASCII.GetString(mRx, 0, nCountReadBytes); printLine(DateTime.Now + " - " + cn.ToString() + ": " + hex); cn.Rx = new byte[30]; tcpc.GetStream().BeginRead(cn.Rx, 0, cn.Rx.Length, onCompleteReadFromTCPClientStream, tcpc); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); lock (mlClientSocks) { printLine("Client disconnected: " + cn.ToString()); mlClientSocks.Remove(cn); lbClients.Items.Remove(cn.ToString()); } } }
private void OnCompleteReadTcpClient(IAsyncResult iar) { TcpClient client = null; int readCount = 0; string recieved = ""; ClientNode cn = null; try { lock (_clientSocks) { client = (TcpClient)iar.AsyncState; cn = _clientSocks.Find(x => x._Id == client.Client.RemoteEndPoint.ToString()); readCount = client.GetStream().EndRead(iar); if (readCount == 0) // happens when disconnected { PrintLine(cn, "Client disconnected"); _clientSocks.Remove(cn); lbClients.Items.Remove(cn.FullId); SendClientDisconnected(cn); return; } recieved = Encoding.ASCII.GetString(cn._Rx, 0, readCount).Trim(); //process reads ProcessClientMessage(cn, new ClientRecieve(recieved)); //recieved = Encoding.ASCII.GetString(_buffer, 0, readCount); cn._Rx = new byte[cn.BufSize]; client.GetStream().BeginRead(cn._Rx, 0, cn._Rx.Length, OnCompleteReadTcpClient, client); } } catch (IOException) { PrintLine(cn, "Client disconnected"); _clientSocks.Remove(cn); lbClients.Items.Remove(cn.FullId); SendClientDisconnected(cn); } catch (Exception ex) { ExceptionMessageHandler(cn, ex); } }
private void SendClientDisconnected(ClientNode cn) { ClientNode acn = null; try { for (int i = 0; i < lbClients.Items.Count; i++) { acn = _clientSocks.Find(x => x.FullId == lbClients.Items[i].ToString()); SendServerMessage(acn, new ServerSend(OperationType.ClientDisconnected, cn.FullId)); } } catch (Exception ex) { ExceptionMessageHandler(cn, ex); } }
//функция отправления сообщения клиенту private void btnSend_Click(object sender, EventArgs e) { try { if (lbClients.Items.Count <= 0) { return; } if (string.IsNullOrEmpty(tbPayload.Text)) { return; } ClientNode cn = null; cn = mlClientSocks.Find(x => x.strId == lbClients.SelectedItem.ToString()); //выбор определённого клиента для отправки сообщения cn.Tx = new byte[100000]; //буффер для отправки lock (mlClientSocks) //lock используется для того,чтобы синхронизировать потоки и ограничить доступ к разделяемым ресурсам на время их использования каким-нибудь потоком. { try { if (cn != null) { if (cn.tclient != null) { if (cn.tclient.Client.Connected) { cn.Tx = Encoding.UTF8.GetBytes(tbPayload.Text); //преобразование Text в byte cn.tclient.GetStream().BeginWrite(cn.Tx, 0, cn.Tx.Length, onCompleteWriteToClientStream, cn.tclient); //отправка сообщения клиенту MessageBox.Show("Сообщение отправлено!"); } } } tbPayload.Text = ""; } catch (Exception exc) { MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch (Exception p) { MessageBox.Show("Выберите получателя для отправки сообщения"); } }
private void btnSend_Click(object sender, EventArgs e) { if (lbClients.Items.Count <= 0) { return; } if (string.IsNullOrEmpty(tbPayload.Text)) { return; } ClientNode cn = null; lock (mlClientSocks) { cn = mlClientSocks.Find(x => x.strId == lbClients.SelectedItem.ToString()); cn.Tx = new byte[8]; try { if (cn != null) { if (cn.tclient != null) { if (cn.tclient.Client.Connected) { cn.Tx[0] = (byte)0x02; cn.Tx[1] = (byte)0x01; cn.Tx[2] = (byte)0x00; cn.Tx[3] = (byte)0x04; cn.Tx[4] = (byte)0x01; cn.Tx[5] = (byte)0x9F; cn.Tx[6] = (byte)0x3C; cn.Tx[7] = (byte)0x03; //cn.Tx = Encoding.ASCII.GetBytes(tbPayload.Text); cn.tclient.GetStream().BeginWrite(cn.Tx, 0, cn.Tx.Length, onCompleteWriteToClientStream, cn.tclient); } } } } catch (Exception exc) { MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private void ProcessClientMessage(ClientNode cn, ClientRecieve cm) { try { switch (cm.OpType) { case OperationType.ServerClientId: break; case OperationType.ClientName: cn.Name = cm.Data; lbClients.Items.Add(String.Format("{0} [{1}]", cn.ToString(), cn.Name)); PrintLine(cn, "HS: recieved client name"); SendServerClientNames(cn); UpdateAllConnectedClients(cn); break; case OperationType.TotalServerClients: break; case OperationType.ServerClientName: break; case OperationType.RouteToServerClient: string[] split = cm.Data.Split(Const.ClientNameDataDeliminator); string clientName = split[0]; // testing cn = _clientSocks.Find(x => x._Id == cn.FullId); SendDataToClient(split[0], OperationType.Message, cm.Data); break; case OperationType.Message: PrintLine(cn, cm.Data); break; default: break; } } catch (Exception ex) { ExceptionMessageHandler(cn, ex); } }
private void BtnVisit_Click(object sender, EventArgs e) { if (lbClients.Items.Count <= 0) { return; } ClientNode cn = null; lbClients.Visible = false; for (int i = 0; i < lbClients.Items.Count; i++) { lbClients.SetSelected(i, true); lock (mlClientSocks) { cn = mlClientSocks.Find(x => x.strId == lbClients.SelectedItem.ToString()); cn.Tx = new byte[512]; try { if (cn != null) { if (cn.tclient != null) { if (cn.tclient.Client.Connected) { cn.Tx = Encoding.ASCII.GetBytes("visit " + txtURL.Text + "?&autoplay=1" + " " + txtVisitsTime.Text); cn.tclient.GetStream().BeginWrite(cn.Tx, 0, cn.Tx.Length, onCompleteWriteToClientStream, cn.tclient); } } } } catch (Exception exc) { MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } lbClients.Visible = true; }
//private void SendData(ClientNode cn, string data) //{ // cn._Tx = Encoding.ASCII.GetBytes(data); // cn._Client.GetStream().BeginWrite(cn._Tx, 0, cn._Tx.Length, OnCompleteWriteTcpClient, cn._Client); //} private void OnCompleteWriteTcpClient(IAsyncResult iar) { ClientNode cn = null; TcpClient client = null; try { lock (_clientSocks) { client = (TcpClient)iar.AsyncState; cn = _clientSocks.Find(x => x._Id == client.Client.RemoteEndPoint.ToString()); //TcpClient client = (TcpClient)iar.AsyncState; cn._Client.GetStream().EndWrite(iar); } } catch (Exception ex) { ExceptionMessageHandler(null, ex); } }
private void btnSend_Click(object sender, EventArgs e) { ClientNode cn = null; if (lbClients.SelectedItem == null) { ErrorMessageHandler("No client selected"); return; } if (tbPayload.Text == "") { ErrorMessageHandler("Payload is empty"); return; } cn = _clientSocks.Find(x => x.FullId == lbClients.SelectedItem.ToString());//.Split(' ')[0]); SendDataToClient(cn.FullId, OperationType.Message, tbPayload.Text); tbPayload.Text = ""; }
private void SendDataToClient(string clientName, OperationType opType, string data) { //byte[] buffer = new byte[_bufLen]; if (lbClients.Items.Count <= 0) { return; } if (string.IsNullOrEmpty(data)) { return; } ClientNode cn = null; lock (_clientSocks) { //cn = _clientSocks.Find(x => x._Id == lbClients.SelectedItem.ToString().Split(' ')[0]); cn = _clientSocks.Find(x => x.FullId == clientName); } cn._Tx = new byte[cn.BufSize]; try { if (cn != null) { if (cn._Client != null) { if (cn._Client.Client.Connected) { SendServerMessage(cn, new ServerSend(opType, data)); //SendData(cn, data); } } } } catch (Exception ex) { ExceptionMessageHandler(cn, ex); } }
private void UpdateAllConnectedClients(ClientNode cn) { ClientNode acn = null; try { for (int i = 0; i < lbClients.Items.Count; i++) { acn = _clientSocks.Find(x => x.FullId == lbClients.Items[i].ToString()); string scid = acn.FullId; if (scid != cn.FullId) { SendServerMessage(acn, new ServerSend(OperationType.NewClientConnected, cn.FullId)); } } } catch (Exception ex) { ExceptionMessageHandler(cn, ex); } }
//функция чтения данных с клиентов void onCompleteReadFromTCPClientStream(IAsyncResult iar) { TcpClient tcpc; int nCountReadBytes = 0; //Количество полученных байт //string strRecv; ClientNode cn = null; //используется для работы с клиентами try { lock (mlClientSocks) { tcpc = (TcpClient)iar.AsyncState; cn = mlClientSocks.Find(x => x.strId == tcpc.Client.RemoteEndPoint.ToString());//выбор определённого клиента для отправки сообщения nCountReadBytes = tcpc.GetStream().EndRead(iar); if (nCountReadBytes == 0) { MessageBox.Show("Client disconnected."); mlClientSocks.Remove(cn); lbClients.Items.Remove(cn.ToString()); return; } printLine(" Text : " + Encoding.UTF8.GetString(cn.Rx, 0, nCountReadBytes).ToString()); if (Encoding.UTF8.GetString(cn.Rx, 0, nCountReadBytes).ToString() == "TIME") { cn.Tx = Encoding.UTF8.GetBytes(DateTime.Now.ToString()); //преобразование Text в byte cn.tclient.GetStream().BeginWrite(cn.Tx, 0, cn.Tx.Length, onCompleteWriteToClientStream, cn.tclient); //отправка сообщения клиенту } else if (Encoding.UTF8.GetString(cn.Rx, 0, nCountReadBytes).ToString() == "CLOSE") { mlClientSocks.Remove(cn); lbClients.Items.Remove(cn.ToString()); } else if (Encoding.UTF8.GetString(cn.Rx, 0, 8).ToString() == "DOWNLOAD") { int nameSize = BitConverter.ToInt32(cn.Rx, 8); string filename = Encoding.UTF8.GetString(cn.Rx, 12, nameSize); int fileSize = BitConverter.ToInt32(cn.Rx, 12 + nameSize); byte[] data = new byte[100000]; //cn.Rx.CopyTo(data, 12+4+fileSize); Array.Copy(cn.Rx, 12 + 4, data, 0, fileSize); File.WriteAllBytes("titylnik.docx", data); } Logger.WriteLine(cn.ToString() + ": " + "Text: " + Encoding.UTF8.GetString(cn.Rx, 0, nCountReadBytes).ToString()); //запись информации в файл cn.Rx = new byte[100000]; tcpc.GetStream().BeginRead(cn.Rx, 0, cn.Rx.Length, onCompleteReadFromTCPClientStream, tcpc); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); lock (mlClientSocks) { printLine("Client disconnected: " + cn.ToString()); mlClientSocks.Remove(cn); lbClients.Items.Remove(cn.ToString()); } } }
//функция отправления массива байт клиенту private void button1_Click(object sender, EventArgs e) { try { ClientNode cn = null; if (lbClients.Items.Count <= 0) { return; } lock (mlClientSocks) { cn = mlClientSocks.Find(x => x.strId == lbClients.SelectedItem.ToString()); //выбор определённого клиента для отправки сообщения cn.Tx = new byte[100000]; //буффер для отправки try { if (cn != null) { if (cn.tclient != null) { if (cn.tclient.Client.Connected) { for (int i = Convert.ToInt32(num1.Text), j = 0; j <= Convert.ToInt32(num3.Text) + 1; i++, j++) { if (i > 255)//если значение i больше чем 255, то находим остаток от деления, и приравниваем этот остаток к i { i %= 256; } if (j == 0)//заполняем наш первый элемен массива символом *(42) { cn.Tx[0] = 42; i = Convert.ToInt32(num1.Text) - 1; continue; } cn.Tx[j] = (byte)(i); //заполняем массив байтов различными значениями i += Convert.ToInt32(num2.Text) - 1; //увеличиваем шаг } for (int i = 0; i < cn.Tx.Length; i++) { if (cn.Tx[i] == 0 && cn.Tx[i + 1] == 0 && cn.Tx[i + 2] == 0)// если 3 подряд значения массива байтов равна 0, то удаляем находим общее количество этих нулей { count = cn.Tx.Length - i; break; } } Array.Resize(ref cn.Tx, cn.Tx.Length - count); //обрезаем нули, которые нам не нужны count = 0; cn.tclient.GetStream().BeginWrite(cn.Tx, 0, cn.Tx.Length, onCompleteWriteToClientStream, cn.tclient); //отправка сообщения клиенту MessageBox.Show("Сообщение отправлено!"); } } } } catch (Exception exc) { MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch (Exception p) { MessageBox.Show("Выберите получателя для отправки сообщения"); } }
private void ExceptionMessageHandler(ClientNode cn, Exception ex) { PrintLine(cn, String.Format("[Exception] {0}", ex.Message)); }
void onCompleteReadFromTCPClientStream(IAsyncResult iar) { TcpClient tcpc; int nCountReadBytes = 0; string strRecv; ClientNode cn = null; try { lock (mlClientSocks) { tcpc = (TcpClient)iar.AsyncState; cn = mlClientSocks.Find(x => x.strId == tcpc.Client.RemoteEndPoint.ToString()); nCountReadBytes = tcpc.GetStream().EndRead(iar); if (nCountReadBytes == 0)// this happens when the client is disconnected { MessageBox.Show("Client disconnected."); mlClientSocks.Remove(cn); lbClients.Items.Remove(cn.ToString()); return; } strRecv = Encoding.ASCII.GetString(cn.Rx, 0, nCountReadBytes).Trim(); string path; path = "C:\\Users\\karim\\Desktop\\" + strRecv; printLine(path); if (File.Exists(path) == true) { /* * //in case of images: * Image mImage = Image.FromFile(path); * SendData(ImageToByte(mImage), cn); */ //in case of html files: SendData(FileToByte(path), cn); } else if (File.Exists(path) == false) { SendData(Encoding.ASCII.GetBytes("ERROR 404 File Not Found!"), cn); } //strRecv = Encoding.ASCII.GetString(mRx, 0, nCountReadBytes); printLine(DateTime.Now + " - " + cn.ToString() + ": " + strRecv); //pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; //pictureBox1.Image = BytesToImg(cn.Rx); //webBrowser1.DocumentText = strRecv; cn.Rx = new byte[200000]; tcpc.GetStream().BeginRead(cn.Rx, 0, cn.Rx.Length, onCompleteReadFromTCPClientStream, tcpc); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); lock (mlClientSocks) { printLine("Client disconnected: " + cn.ToString()); mlClientSocks.Remove(cn); lbClients.Items.Remove(cn.ToString()); } } }
private void SendServerClientID(ClientNode cn) { SendServerMessage(cn, new ServerSend(OperationType.ServerClientId, cn.ToString())); PrintLine(cn, "HS: send server client id to client"); }