Добавление байтов при создании сокета - C#
Формулировка задачи:
Читаю книгу dotNET Сетевое программирование для профессионалов,но то,что мне нужно я не нашел(нашел почти все,что нужно но некоторых вещей нет)
Устанавливаю соединение с сервером, далее нужно отправить пакет, заканчивающийся на 0A 00
Вот мой код:
Как видите, я не добавляю в конец пакета 0x0A и 0x00, а надо иначе сервер возвратит ошибку,точнее не ошибку а не верный ответ.
Как добавить в конец сокета нужные мне байты?
IPHostEntry ipHOST = Dns.Resolve("62.146.190.34"); IPAddress ipaddr = ipHOST.AddressList[0]; IPEndPoint ipEP = new IPEndPoint(ipaddr, 8080); Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sender.Connect(ipEP); Console.WriteLine("Socket подключился к {0}", sender.RemoteEndPoint.ToString()); string whyME = "LOGIN|35055730|7ba003de04cf97ee3c7844c259c672ed|4.3.1..PNG"; byte[] msg = Encoding.ASCII.GetBytes(whyME); int bytessend = sender.Send(msg); int bytesRec = sender.Receive(whToSend); Console.WriteLine("Сервер ответил: {0}", Encoding.ASCII.GetString(whToSend, 0, bytesRec)); sender.Shutdown(SocketShutdown.Both); sender.Close();
Решение задачи: «Добавление байтов при создании сокета»
textual
Листинг программы
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Windows.Forms; //Implements a sample socket client to connect to the server implmented in the AsyncSocketServer project //Usage: AsyncSocketClient.exe <destination IP address> <destination port number> //Destination IP address: The IP Address of the server to connect to //Destination Port Number: The port number to connect to namespace AsyncSocketClient { class AsyncSocketClientProgram { static ManualResetEvent clientDone = new ManualResetEvent(false); static void Activate(string[] args) { IPAddress destinationAddr = null; // IP Address of server to connect to int destinationPort = 0; // Port number of server SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs(); if (args.Length != 2) { MessageBox.Show("Usage: AsyncSocketClient.exe <destination IP address> <destination port number>"); } try { destinationAddr = IPAddress.Parse(args[0]); destinationPort = int.Parse(args[1]); if (destinationPort <= 0) { throw new ArgumentException("Destination port number provided cannot be less than or equal to 0"); } } catch (Exception e) { MessageBox.Show(e.Message); MessageBox.Show("Usage: AsyncSocketClient.exe <destination IP address> <destination port number>"); } // Create a socket and connect to the server Socket sock = new Socket(destinationAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArg_Completed); socketEventArg.RemoteEndPoint = new IPEndPoint(destinationAddr, destinationPort); socketEventArg.UserToken = sock; sock.ConnectAsync(socketEventArg); clientDone.WaitOne(); } /// <summary> /// A single callback is used for all socket operations. This method forwards execution on to the correct handler /// based on the type of completed operation /// </summary> static void SocketEventArg_Completed(object sender, SocketAsyncEventArgs e) { switch (e.LastOperation) { case SocketAsyncOperation.Connect: ProcessConnect(e); break; case SocketAsyncOperation.Receive: ProcessReceive(e); break; case SocketAsyncOperation.Send: ProcessSend(e); break; default: throw new Exception("Invalid operation completed"); } } /// <summary> /// Called when a ConnectAsync operation completes /// </summary> private static void ProcessConnect(SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { MessageBox.Show("Successfully connected to the server"); byte[] buffer = Encoding.UTF8.GetBytes("Hello .......>\n\r"); e.SetBuffer(buffer, 0, buffer.Length); Socket sock = e.UserToken as Socket; bool willRaiseEvent = sock.SendAsync(e); if (!willRaiseEvent) { ProcessSend(e); } } else { throw new SocketException((int)e.SocketError); } } /// <summary> /// Called when a ReceiveAsync operation completes /// </summary> //sourth - private static void ProcessReceive(SocketAsyncEventArgs e) private static string ProcessReceive(SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { string StrReceive = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred); MessageBox.Show("Received from server: {0}", Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred)); // Data has now been sent and received from the server. Disconnect from the server //ne zakryvayu poka socket Socket sock = e.UserToken as Socket; sock.Shutdown(SocketShutdown.Send); sock.Close(); clientDone.Set(); return StrReceive; } else { throw new SocketException((int)e.SocketError); } } /// <summary> /// Called when a SendAsync operation completes /// </summary> private static void ProcessSend(SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { MessageBox.Show("Sent 'Hello World' to the server"); //Read data sent from the server Socket sock = e.UserToken as Socket; bool willRaiseEvent = sock.ReceiveAsync(e); if (!willRaiseEvent) { ProcessReceive(e); } } else { throw new SocketException((int)e.SocketError); } } } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д