Socket Server/Client. Падение клиента при коннекте к серверу - C#

Узнай цену своей работы

Формулировка задачи:

В общем есть сервер:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
 
namespace Server
{
    class Program
    {
        static List<EndPoint> sockets = new List<EndPoint>();
        static string textToSend = null;
        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);
                sockets.Add (client.RemoteEndPoint);
                Console.WriteLine("Новый клиент: {0}", client.RemoteEndPoint);
                AsyncState state = new AsyncState { socket = client, buffer = new byte[client.ReceiveBufferSize] };
                byte[] data = Encoding.UTF8.GetBytes("Здравствуйте");
                client.BeginReceive(state.buffer, 0, state.buffer.Length, SocketFlags.None, ReceiveCallback, state);
                client.BeginSend(data, 0, data.Length, SocketFlags.None, SendCallback, 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);
                    textToSend = state.socket.RemoteEndPoint.ToString() +"  "+ text;

                    Console.WriteLine("{0}: {1}", state.socket.RemoteEndPoint, text);
                    byte[] answer = Encoding.UTF8.GetBytes(textToSend);
                    for (int i = 0; i < sockets.ToArray().Length; i++)
                    {
                        System.Threading.Thread.Sleep(100);
                        state.socket.BeginSendTo(answer, 0, answer.Length, SocketFlags.None, sockets[i], 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);

                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;
    }
}
и клиент
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace Client
{
    class Program
    {
        static Socket sck;
        static byte[] buffer;
 
        static void Main(string[] args)
        {
            Socket accept = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5080);

                sck.BeginConnect(endpoint,ReceiveCallback,sck);
                Console.WriteLine("Connectin Succes");

        }

        static void ReceiveCallback(IAsyncResult iar)
        {
            AsyncState state = (AsyncState)iar.AsyncState;
 
            byte[] data = state.buffer;
            state.socket.Receive(data);
 
            try
            {
                int recv = state.socket.EndReceive(iar);
                
                string text = Encoding.UTF8.GetString(state.buffer, 0, recv);
                Console.WriteLine(text);

            }
            
            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);

                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;
    }
}
При конекте клиента к серверу консоль сразу же закрывается (в логе сервера клиент подсоединяется и сразу же закрывается). Что я не так делаю?

Решение задачи: «Socket Server/Client. Падение клиента при коннекте к серверу»

textual
Листинг программы
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
 
// State object for receiving data from remote device.
public class StateObject
{
    // Client socket.
    public Socket workSocket = null;
    // Size of receive buffer.
    public const int BufferSize = 256;
    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];
    // Received data string.
    public StringBuilder sb = new StringBuilder();
}
 
public class Client
{
    // The port number for the remote device.
    private const int port = 5080;
 
    // ManualResetEvent instances signal completion.
    private static ManualResetEvent connectDone =
        new ManualResetEvent(false);
    private static ManualResetEvent sendDone =
        new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =
        new ManualResetEvent(false);
 
    static byte[] data;
    static Socket sck;
 
 
 
    public static void Main()
    {
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint end = new IPEndPoint(IPAddress.Parse("127.0.0.1"),5080);
 
        sck.BeginConnect(end, ConnectCallBack, sck);
 
    }
 
    static void ConnectCallBack(IAsyncResult iar){
        
        Socket client = (Socket)iar.AsyncState;
        AsyncState state = new AsyncState { socket = client, buffer = new byte[client.ReceiveBufferSize] };
 
        String textdata = "привет";
        byte[] data = Encoding.UTF8.GetBytes(textdata) ;
        try
        {
            client.EndConnect(iar);
            state.socket.BeginSend(data, 0, data.Length, SocketFlags.None, SendCallback, state);
            connectDone.Set();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
 
   static void SendCallback(IAsyncResult iar)
        {
            AsyncState state = (AsyncState)iar.AsyncState;
            try
            {
                int sent = state.socket.EndSend(iar);
 
               
                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();
            }
        }
    
 
    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(text);
               
                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();
        }
    }
 
    struct AsyncState
    {
        public Socket socket;
        public byte[] buffer;
    }
}

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 4.2 из 5
Похожие ответы