0

I am trying to create network application in C# by establishing communication by creating TCP server and client application.

But I am keep getting the Exception:

"An existing connection was forcibly closed by the remote host" on the line: int bytesReceived = clientsocket.Receive(dataRecieved);

Can Anyone help me resolve this error. Here is My code:

Client Code:

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


}

}

Server Code:

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

}

DataBase class:

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

}

David Gardner
  • 149
  • 1
  • 10
  • Perhaps take a look at [this SO question](https://stackoverflow.com/questions/2582036/an-existing-connection-was-forcibly-closed-by-the-remote-host) – Cubemaster Nov 14 '18 at 18:59
  • 1
    Possible duplicate of [An existing connection was forcibly closed by the remote host](https://stackoverflow.com/questions/2582036/an-existing-connection-was-forcibly-closed-by-the-remote-host) – Cubemaster Nov 14 '18 at 19:00

0 Answers0