Исключение «Существующее соединение было принудительно закрыто удаленным узлом» в приложении WPF - PullRequest
0 голосов
/ 14 ноября 2018

Я пытаюсь создать сетевое приложение на C #, установив связь путем создания TCP-сервера и клиентского приложения.

Но я получаю исключение:

«Существующее соединение было принудительно закрыто удаленным хостом» на линии: int bytesReceived = clientsocket.Receive (dataReceve);

Может ли кто-нибудь помочь мне решить эту ошибку. Вот мой код:

Код клиента:

namespace Client
             {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    string text;
    public static Socket clientsocket;
    public MainWindow()
    {
        InitializeComponent();
    }

    private void connectbutton_Click(object sender, RoutedEventArgs e)
    {
        IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
        int port = 11000;
        IPEndPoint remoteEndPoint = new IPEndPoint(ipaddress, port);
        clientsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        clientsocket.Connect(remoteEndPoint);
    }

    private void search_btn_Click(object sender, RoutedEventArgs e)
    {
        text = ((TextBox)grid.FindName("search")).Text;
        byte[] datasent = Encoding.ASCII.GetBytes(text);
        int bytesent = clientsocket.Send(datasent);
        byte[] dataRecieved = new byte[10 * 1024];
        int bytesReceived = clientsocket.Receive(dataRecieved);
        DataTable table = Deserailize(dataRecieved);
    }
    private static DataTable Deserailize(byte[] dataRecieved)
    {
        System.IO.MemoryStream stream = new System.IO.MemoryStream(dataRecieved);
        System.Runtime.Serialization.IFormatter formatter = new System.Runtime.
        Serialization.Formatters.Binary.BinaryFormatter();
        DataTable table = (DataTable)formatter.Deserialize(stream);
        return table;
    }


}

}

Код сервера:

      namespace Server
         {
class Program
{
    static void Main(string[] args)
    {
        IPAddress ipaddress =  IPAddress.Parse("127.0.0.1");
        int port = 11000;
        IPEndPoint localEndPoint = new IPEndPoint(ipaddress, port);
        Socket connectionsocket = null;
        try
        {
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(localEndPoint);
            serverSocket.Listen(1);
            Console.WriteLine("Waiting For Connection");
            connectionsocket = serverSocket.Accept();
            Console.WriteLine("Connection Accepted");
            while(true)
            {
                byte[] bytes = new byte[1024];
                int byterecieved = connectionsocket.Receive(bytes);
                string text = Encoding.ASCII.GetString(bytes, 0, byterecieved);
                DataTable table = DB.getCustomer(text);
                byte[] bytessent= serailize(table);
                connectionsocket.Send(bytessent);
            }
        }
        catch (Exception e)
        {

        }
    }
    private static byte[] serailize(DataTable table)
    {
        System.IO.MemoryStream stream = new System.IO.MemoryStream();
        System.Runtime.Serialization.IFormatter formatter = new System.Runtime.
        Serialization.Formatters.Binary.BinaryFormatter();
        formatter.Serialize(stream, table);
        byte[] byteArray = stream.GetBuffer();
        return byteArray;
    }
}

}

Класс базы данных:

class DB
{
    public static SqlConnection con = new SqlConnection();
    public static string ConnectionString = @"Data Source=DESKTOP-9CG0F5H;Initial Catalog=worksheet3;Integrated Security=True";
    static DB()
    {
        con = new SqlConnection(ConnectionString);
        con.Open();
    }
    public static DataTable getCustomer(string text)
    {
        SqlCommand command = new SqlCommand();
        command.Connection = con;
        command.CommandText = "Select * from Student where StudentName=@StudentName";
        SqlDataAdapter adaptor = new SqlDataAdapter(command);
        DataTable table = new DataTable();
        adaptor.Fill(table);
        return table;
    }
}
* *} Тысяча двадцать-один
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...