.NET 4.x Задача: сделать сервер для нескольких клиентов - C#
Формулировка задачи:
Вот есть сервер, который рассчитан только на 1 клиент. Задача: сделать сервер для нескольких клиентов. Как это сделать?
Сам сервер:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace Server { class Program { static byte[] buffer; static Socket sck; static void Main(string[] args) { sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp); sck.Bind(new IPEndPoint(0, 5080)); sck.Listen(100); Socket accepted = sck.Accept(); while (true) { string unswer = "Server accept the message..."; buffer = new byte[accepted.SendBufferSize]; int bytesCount = accepted.Receive(buffer); byte[] formated = new byte[bytesCount]; for (int i = 0; i < bytesCount; i++) { formated[i] = buffer[i]; } string text = Encoding.UTF8.GetString(formated); Console.Write(text + "\n\r"); byte[] dataSend = Encoding.UTF8.GetBytes(unswer); accepted.Send(dataSend); } Console.Read(); sck.Close(); accepted.Close(); } } }
Решение задачи: «.NET 4.x Задача: сделать сервер для нескольких клиентов»
textual
Листинг программы
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; namespace AsyncTcpServer { class Program { static void Main() { Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.Bind(new IPEndPoint(IPAddress.Any, 5080)); server.Listen(100); server.BeginAccept(ConnectCallback, server); string input; Console.WriteLine("Type 'exit' to quit"); while ((input = Console.ReadLine().ToLower()) != "exit") ; } static void ConnectCallback(IAsyncResult iar) { Socket server = (Socket)iar.AsyncState; try { Socket client = server.EndAccept(iar); Console.WriteLine("New client connected: {0}", client.RemoteEndPoint); AsyncState state = new AsyncState { socket = client, buffer = new byte[client.ReceiveBufferSize] }; client.BeginReceive(state.buffer, 0, state.buffer.Length, SocketFlags.None, ReceiveCallback, state); } catch (SocketException e) { Console.WriteLine("Error accepting connection: {0}", e.Message); } server.BeginAccept(ConnectCallback, server); } static void ReceiveCallback(IAsyncResult iar) { AsyncState state = (AsyncState)iar.AsyncState; try { int recv = state.socket.EndReceive(iar); if (recv == 0) { Console.WriteLine("Client {0} has closed connection", state.socket.RemoteEndPoint); state.socket.Close(); } else { string text = Encoding.UTF8.GetString(state.buffer, 0, recv); Console.WriteLine("{0}: {1}", state.socket.RemoteEndPoint, text); byte[] answer = Encoding.UTF8.GetBytes("Server accepted the message..."); state.socket.BeginSend(answer, 0, answer.Length, SocketFlags.None, SendCallback, state); } } catch (SocketException e) { Console.WriteLine("Error receiving from {0}: {1}", state.socket.RemoteEndPoint, e.Message); state.socket.Close(); } } static void SendCallback(IAsyncResult iar) { AsyncState state = (AsyncState)iar.AsyncState; try { int sent = state.socket.EndSend(iar); Console.WriteLine("Sent {0} bytes to {1}", sent, state.socket.RemoteEndPoint); state.socket.BeginReceive(state.buffer, 0, state.buffer.Length, SocketFlags.None, ReceiveCallback, state); } catch (SocketException e) { Console.WriteLine("Error sending to {0}: {1}", state.socket.RemoteEndPoint, e.Message); state.socket.Close(); } } } struct AsyncState { public Socket socket; public byte[] buffer; } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д