none
How to make winsock control to connect client application and server application in c# windows forms RRS feed

  • Question

  • Hi my name is vishal for past 2 days i have been breaking my head on how to make my winsock control to connect client application and server application in c# windows forms with sql server 2008?

    I have developed a client application named:Winsock client and which has a form named:Form1

    Given below is my screen-shot of Form1 of Winsock client:

    So i have 3 buttons

    1st button name:btnSend,enabled:true,text:Lookup and visible:true

    2nd button name:btnConnect,enabled:true,text:Connect and visible:true

    3rd button name:btnDisconnect,enabled:true,text:Close and visible:true

    2 textboxes

    1st textbox name:txtItem,enabled:true,MultiLine:false and visible:true

    2nd textbox name:txtPrice,enabled:true,MultiLine:false and visible:true

    1 winsock control named:Winsock1,BytesReceived:0,CtlState:0-sckClosed,LocalHostName:NPD-4,LocalIP:192.168.0.104,Protocol:0-sckTCPProtocol and visible:true

    1 label name:label3,text:""(null),enabled:true and visible:true

    3OvalShape controls

    1st OvalShape name:shpGo,FillColor:Lime,enabled:true,FillStyle:Solid and visible:false

    2nd OvalShape:shpWait,FillColor:Yellow,enabled:true,FillStyle:Solid and visible:false

    3rd OvalShape:shpError,FillColor:Red,enabled:true,FillStyle:Solid and visible:false

    Given below is c# code of my Form1 of Winsock client:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;
    using System.Data.SqlClient;
    using System.Diagnostics;
    using System.Net;
    using System.Net.Sockets;
    namespace Winsock_client
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            private void btnSend_Click(object sender, EventArgs e)
            {
                if (Winsock1.CtlState == 2)
                {
                    byte[] abData;
                    string str = txtPrice.Text;
                    abData = System.Text.ASCIIEncoding.Default.GetBytes(str);
    
                    Winsock1.SendData(txtPrice.Text);
                    shpGo.Visible = true;
                    label3.Text = "Sending Data";
                }
                else
                {
                    shpGo.Visible = false;
                    shpWait.Visible = false;
                    shpError.Visible = true;
                    label3.Text = "Not currently connected to host";
                }
            }
            private void btnDisconnect_Click(object sender, EventArgs e)
            {
                Winsock1.Close();
                shpGo.Visible=false;
                shpWait.Visible =false;
                shpError.Visible = false;
            }
            private void btnConnect_Click(object sender, EventArgs e)
            {
                Winsock1.RemoteHost = "192.168.0.104"; //Change this to your host ip
                Winsock1.RemotePort = 7777;
                Winsock1.Connect();
                shpGo.Visible=true;
                txtPrice.Focus();
            }
            private void Winsock1_DataArrival(object sender, AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent e)
            {
                string sData="";
                Object cand = (object)sData;
                Winsock1.GetData(ref cand);
                cand = (String)sData;
                txtPrice.Text = sData;
                label3.Text = "Received Data";
                shpGo.Visible = true;
                shpWait.Visible = false;
                shpError.Visible = false;
            }
            private void Winsock1_SendComplete(object sender, EventArgs e)
            {
                label3.Text = "Completed Data Transmission";
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
    
            }
        }
    }

    I have also developed a server application named:Winsock server which has a form named:Form1

    Given below is screen-shot of Form1 of Winsock server:

    So 1 listbox name:listBox1,enabled:true,MultiColumn:false,SelectionMode:One and visible:true

    3textboxes

    1st textbox name:txtHostID,enabled:true,MultiLine:false and visible:true

    2nd textbox name:txtAddress,enabled:true,MultiLine:false and visible:true

    3rd textbox name:txtConnections,enabled:true,MultiLine:false and visible:true

    1winsock control name:Socket,BytesReceived:0,CtlState:0-sckClosed,LocalHostName:NPD-4,LocalIP:192.168.0.104,Protocol:0-sckTCPProtocol and visible:true

    Given below is c# code of my Form1 of Winsock server:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;
    using System.Diagnostics;
    using System.Data.SqlClient;
    using System.Net;
    using System.Net.Sockets;
    using System.IO.Compression;
    namespace Winsock_server
    {
        public partial class Form1 : Form
        {
            int iSockets;
            string sServerMsg;
            string sRequestID;
            Socket sck;
            public Form1()
            {
                InitializeComponent();
                sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            }
            private string GetLocalIP()
            {
                IPHostEntry host;
                host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return ip.ToString();
                    }
                }
                return "127.0.0.1";
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                txtHostID.Text = Socket.LocalHostName;
                txtAddress.Text = Socket.LocalIP;
                Socket.LocalPort = 7777;
                sServerMsg = "Listening to port: " + Socket.LocalPort;
                listBox1.Items.Add(sServerMsg);
                Socket.Listen();
            }
            private void Socket_CloseEvent(object sender, EventArgs e)
            {
                sServerMsg = "Connection closed: " + Socket.RemoteHostIP;
                listBox1.Items.Add(sServerMsg);
                Socket.Close();
                iSockets = iSockets - 1;
                txtConnections.Text = Convert.ToString(iSockets);
            }
            private void Socket_ConnectionRequest(object sender, AxMSWinsockLib.DMSWinsockControlEvents_ConnectionRequestEvent e)
            { 
                sServerMsg = "Connection request id " + e.requestID + " from " + Socket.RemoteHostIP;
                listBox1.Items.Add(sServerMsg);
                sRequestID = e.requestID.ToString();
                iSockets = iSockets + 1;
                txtConnections.Text = iSockets.ToString();
            }
            private void Socket_DataArrival(object sender, AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent e)
            {
                string sItemData = "";
                string strData;
                string strOutData;
                Object rend = (object)sItemData;
                Socket.GetData(ref rend);
                sItemData = (String)rend;
                sServerMsg = "Received: " + sItemData + " from " + Socket.RemoteHostIP + "(" + sRequestID + ")";
                listBox1.Items.Add(sServerMsg);
                SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Winsock;Integrated Security=true");
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                string price = ("Select Price from Prices");
                SqlCommand hdc = new SqlCommand(price);
                hdc.Connection = conn;
                hdc.CommandType = CommandType.Text;
                SqlDataReader dx = hdc.ExecuteReader();
                while (dx.Read())
                {
                    if (dx[1].ToString() == sItemData)
                    {
                        strOutData = dx[1].ToString();
                        {
                        }
                        sServerMsg = "Sending: " + strOutData + " to " + Socket.RemoteHostIP;
                        listBox1.Items.Add(sServerMsg);
                        byte[] abData;
                        string str = strOutData;
                        abData = System.Text.ASCIIEncoding.Default.GetBytes(str);
                        Socket.SendData(strOutData);
                    }
                }
            }
        }
    }

    So i have to use only winsock control only for client application and server application communication because of my BOSS's order and that i cannot use classes associated with System.Net.Sockets.

    So when i run Winsock client and Winsock server simultaneously for client server communication the above c# code of Winsock client and Winsock server works only partially as when i press/click btnConnect in Winsock client it works and i get appropriate result of connection request in Winsock server! But here is the problem after connection when i input some text in txtPrice in Form1 of Winsock client and when i press/click btnSend i get error  and message in my label3 in Form1 of Winsock client telling "Not currently connected to host" which points to code below in Form1 of Winsock client Given below is code:

    private void btnSend_Click(object sender, EventArgs e)
            {
                if (Winsock1.CtlState == 2)
                {
                    byte[] abData;
                    string str = txtPrice.Text;
                    abData = System.Text.ASCIIEncoding.Default.GetBytes(str);
                    Winsock1.SendData(txtPrice.Text);
                    shpGo.Visible = true;
                    label3.Text = "Sending Data";
                }
                else
                {
                    shpGo.Visible = false;
                    shpWait.Visible = false;
                    shpError.Visible = true;
                    label3.Text = "Not currently connected to host";
                }
            }

    So my question is how to make my winsock control named:Winsock1 of Form1 of Winsock client to connect to Form1 of Winsock server which contains a winsock control named:Socket.?

    Can anyone help on how to make my winsock(Winsock1) control of Winsock client to connect to Winsock server ? Can anyone tell me what modifications must i do in my c# code to achieve my required result? Can anyone help me please! Any help/guidance in solving of this problem would be greatly appreciated!


    vishal

    Friday, July 11, 2014 7:18 AM

All replies

  • Hi my name is vishal.I at transition from vb6 adodb with Ms access to c# windows forms with sql server2008. I am in process of creating client-server application(client to server communication) in c# windows forms using Winsock control. I have to use winsock control for this purpose since it is my BOSS's orders.

    Any way i have tried a sample of client-server application in c# windows forms using Winsock control.

    So i have a client application named:DRRS Socket in it i have a windows form named:Form1.

    In Form1 i have 1 listbox named:listBox1,enabled:true,MultiColumn:false,SelectionMode:One,visible:true.

    3textboxes

    1st textbox name:textBox1,enabled:true,Multiline:true and visible:true

    2nd textbox name:textBox2,enabled:true,Multiline:true and visible:true

    3rd textbox name:textBox3,enabled:true,Multiline:true and visible:true

    3 Winsock controls

    1st winsock control name:Winsock1,BytesReceived:0,CtlState:0-sckClosed,LocalHostName:NPD-4,LocalIP:192.168.0.106,LocalPort:0,Protocol:0-sckTCPProtocol and visible:true.

    2nd winsock control name:sckServer,BytesReceived:0,CtlState:0-sckClosed,LocalHostName:NPD-4,LocalIP:192.168.0.106,LocalPort:0,Protocol:0-sckTCPProtocol and visible:true.

    3rd winsock control name:sckClient,,BytesReceived:0,CtlState:0-sckClosed,LocalHostName:NPD-4,LocalIP:192.168.0.106,LocalPort:0,Protocol:0-sckTCPProtocol and visible:true.

    3button controls

    1st button control name:button1,enabled:true,text:Get IP Address and visible:true

    2nd button control name:button2,enabled:true,text:Start Listen and visible:true

    3rd button control name:button3,enabled:true,text:Send and visible:true

    Given below is my c# code of Form1 of application DRRS Socket:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Diagnostics;
    namespace DRRS_Socket
    {
        public partial class Form1 : Form
        {
            Socket sck;
            const string DELIM = "***";
            const string EOP = "???";
            public Form1()
            {
                InitializeComponent();
                sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            }
            private string GetLocalIP()
            {
                IPHostEntry host;
                host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return ip.ToString();
                    }
                }
                return "127.0.0.1";
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                int c;
                for (c = 1; c < 20; c++)
                {
                    StartListen();
                }
            }
    public void StartListen()
            {
                sckServer.Close();
                sckServer.LocalPort = 25000;
                sckServer.Listen();
            }
            private void listBox1_Click(object sender, EventArgs e)
            {
                IPHostEntry host;
                host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        textBox1.Text = listBox1.SelectedItem.ToString();
                    }
                }    
            }
    private void button1_Click(object sender, EventArgs e)
            {
                listBox1.Items.Add("127.0.0.1");
                listBox1.Items.Add(GetLocalIP());
            }
    private void button2_Click(object sender, EventArgs e)
            {
                Winsock1.Close();
                Winsock1.Connect(textBox1.Text, textBox2.Text);
                listBox1.Items.Add("Connecting...");
            }
    private void Winsock1_ConnectEvent(object sender, EventArgs e)
            {
                listBox1.Items.Add("Sending...");
                string strPacket;
                strPacket = "Checking from other" + DELIM + "Data1" + DELIM + "Data2" + DELIM + "Data3" + EOP;
                if (Winsock1.CtlState == 2)
                {
    
                    Winsock1.SendData(strPacket);
                    Debug.WriteLine("-->" + strPacket);
                }
                listBox1.Items.Add("Sent."); 
            }
    private void Winsock1_DataArrival(object sender, AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent e)
            {
                byte[] strData=new byte[50];
                Object buffer = (object)strData;
                Winsock1.GetData(ref buffer);
                 string Mstr="";
                for(int i=0;i==strData.GetUpperBound(0);i++)
                {
    
                Mstr = Mstr + Convert.ToString(strData[i]);
                }
                listBox1.Items.Add(Mstr);
            }
    private void Winsock1_Error(object sender, AxMSWinsockLib.DMSWinsockControlEvents_ErrorEvent e)
            {
                Winsock1.Close();
                listBox1.Items.Add(e.description);
            }
    private void sckServer_ConnectionRequest(object sender, AxMSWinsockLib.DMSWinsockControlEvents_ConnectionRequestEvent e)
            {
                    if (sckClient.CtlState != 2)
                    {
                        sckClient.Close();
                        sckClient.Accept(e.requestID);
                        sckClient.SendData("Connected");
                    }
            }
    private void sckClient_Error(object sender, AxMSWinsockLib.DMSWinsockControlEvents_ErrorEvent e)
            {
                sckClient.Close();
                listBox1.Items.Add(e.description);
            }
    private void sckClient_DataArrival(object sender, AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent e)
            {
               byte[] strData=new byte[40];
                Object buffer2 = (object)strData;
                sckClient.GetData(ref buffer2);
                string Mstr="";
                int i;
                for(i=0;i==strData.GetUpperBound(0);i++)
                {
                Mstr = Mstr + Convert.ToString(strData[i]);
                }
                listBox1.Items.Add(Mstr);
            }
    private void sckClient_CloseEvent(object sender, EventArgs e)
            {
                sckClient.Close();
            }
    private void button3_Click(object sender, EventArgs e)
            {
                byte[] abData;
                string Str;
                int i;
                Str = textBox3.Text;
                abData = System.Text.ASCIIEncoding.Default.GetBytes(Str);
                sckClient.SendData(abData);
            }
    }}
    

    The above code executes well to some extent as i dont get any compilation/run-time errors so far.

    I have also developed a server application named:DRRS CSharp in it i have a mdi parent form named:MDIParent1 and a child form named:frmGetSystemData.

    In my form(frmGetSystemData)

    i have 2listbox controls

    1st listbox name:lstIP,enabled:true,MultiColumn:false,SelectionMode:One and visible:true

    2nd listbox name;lstDialyzerID,enabled:true,MultiColumn:false,SelectionMode:One and visible:true

    1textbox control named:txtData,enabled:true,Multiline:true and visible:true

    Given below is  c# code of my form load event of frmGetSystemData:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Net;
    using System.Net.Sockets;
    namespace DRRS_CSharp
    {
        public partial class frmGetSystemData : Form
        {
            string ipAddress;
            const string dConPort = "10000";
    public bool dBOOL = false;
            Socket sck;
            EndPoint epLocal;
     public frmGetSystemData()
            {
                InitializeComponent();
               sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);  
            }
            private string GetLocalIP()
            {
                IPHostEntry host;
                host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return ip.ToString();
                    }
                }
                return "127.0.0.1";
            }
    private void frmGetSystemData_Load(object sender, EventArgs e)
            {
                MDIParent1 t=new MDIParent1();
                SqlConnection cont = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=DRRS;Integrated Security=true");
                if (cont.State != ConnectionState.Open)
                {
                    cont.Open();
                }
                lstIP.Items.Clear();
    SqlCommand hrd = new SqlCommand();
                DataSet ac;
                DataTable mt = new DataTable();
                SqlDataAdapter hcp = new SqlDataAdapter();
                hrd = new SqlCommand("Select ManufacturerName,DCS_ip_address from Reprocess where DCS_ip_address='" + GetLocalIP() + "'", cont);
                hcp = new SqlDataAdapter(hrd);
                ac = new DataSet();
                hcp.Fill(ac, "Reprocess");
                mt = ac.Tables["Reprocess"];
                for (int j = 0; j < mt.Rows.Count; j++)
                {
                    if (mt.Rows[j].ItemArray[1].ToString() ==t.sckClient.RemoteHostIP )
                    {
                        lstIP.Items.Add(mt.Rows[j].ItemArray[0].ToString() + "-" + mt.Rows[j].ItemArray[1].ToString());
                        dBOOL = true;
                    }
                    else
                    {
                        if (dBOOL == false)
                        {
                            MessageBox.Show("No machines are connected.", "DRRS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
    }
    SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=DRRS;Integrated Security=true");
                    if (conn.State != ConnectionState.Open)
                    {
                        conn.Open();
                    }
                    lstDialyzerID.Items.Clear();
                    SqlCommand cmd = new SqlCommand();
                    DataSet ds;
                    DataTable dt = new DataTable();
                    SqlDataAdapter adp = new SqlDataAdapter();
                    cmd = new SqlCommand("Select d.dialyserID,pn.patient_id,pn.patient_first_name,pn.patient_last_name from dialyser d,patient_name pn where d.closed_status=0 and d.deleted_status=0 and pn.patient_id=d.patient_id and pn.status=1", conn);
                    adp = new SqlDataAdapter(cmd);
                    ds = new DataSet();
                    adp.Fill(ds, "dialyser");
                    adp.Fill(ds, "patient_name");
                    dt = ds.Tables["dialyser"];
                    dt = ds.Tables["patient_name"];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        lstDialyzerID.Items.Add(dt.Rows[i].ItemArray[0].ToString() + "|" + dt.Rows[i].ItemArray[2].ToString() + " " + dt.Rows[i].ItemArray[3].ToString() + "-" + string.Format("000" + dt.Rows[i].ItemArray[1].ToString()));
                    }
                }
    }

    The above code works perfectly as i expect it.

    In my MDIParent1(mdi form) i have 3 winsock controls

    1st winsock control name:Winsock1,CtlState:0-sckClosed,LocalHostName:NPD-4,LocalIP:192.168.0.106,LocalPort:0,Protocol:1-sckUDPProtocol and visible:true

    2nd winsock control name:sckServer,CtlState:0-sckClosed,LocalHostName:NPD-4,BytesReceived:0,LocalIP:192.168.0.106,LocalPort:0,Protocol:0-sckTCPProtocol and visible:true

    3rd winsock control name:sckClient,CtlState:0-sckClosed,LocalHostName:NPD-4,BytesReceived:0,LocalIP:192.168.0.106,LocalPort:0,Protocol:0-sckTCPProtocol and visible:true

    Given below is my c# code of Winsock1 connect event:

    frmProgress p = new frmProgress();
                p.lblProgress.Text = "Connection was successful.Waiting for the acknowledgement";
                p.prgVal.Value = 0;
                p.timer1.Enabled = false;
                p.Text = Winsock1.RemoteHostIP + " is connected";
    frmGetSystemData g = new frmGetSystemData();
                g.btnUpdateDialyzer.Enabled = false;
               
                MessageBox.Show(Winsock1.RemoteHostIP + "is connected", "DRRS", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    

    Given below is my c# code for MDIParent1:

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; using iTextSharp.text; using iTextSharp.text.pdf; using System.Diagnostics; using System.IO; using System.Collections; using System.Net; using System.Net.Sockets; using System.Collections.ObjectModel; using System.Linq.Expressions; namespace DRRS_CSharp { public partial class MDIParent1 : Form { public ArrayList pCollConn=new ArrayList(); int DCSrequestID; const string dConPort = "25000"; Socket sck; EndPoint epLocal; public MDIParent1() { InitializeComponent(); sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); } private string GetLocalIP() { IPHostEntry host; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { return ip.ToString(); } } return "127.0.0.1"; } public string getMachineName(string ipLocal) { SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=DRRS;Integrated Security=true"); if (conn.State != ConnectionState.Open) { conn.Open(); } string returnStr; returnStr = ipLocal; frmGetSystemData g = new frmGetSystemData(); string local = ("Select ManufacturerName from Reprocess where DCS_ip_address='" + GetLocalIP() + "'"); SqlCommand dcd = new SqlCommand(local); dcd.Connection = conn; dcd.CommandType = CommandType.Text; SqlDataReader cr = dcd.ExecuteReader(); while (cr.Read()) { returnStr = cr[0].ToString(); } g.lstIP.Items.Add(returnStr); conn.Close(); returnStr = getMachineName(ipLocal); return getMachineName(ipLocal); }

     private void MDIParent1_Load(object sender, EventArgs e)
            {

     connBuilder = new SqlConnectionStringBuilder();
                connBuilder.InitialCatalog = "DRRS";
                connBuilder.DataSource = "NPD-4\\SQLEXPRESS";
                connBuilder.IntegratedSecurity = true;
                connBuilder.AsynchronousProcessing = true;

                conn = new SqlConnection(connBuilder.ToString());
                conn.Open();

    StartListen();

    }

     public void StartListen()
            {
                sckServer.Close();
                sckServer.LocalPort = 10000;
                sckServer.Listen();
                return;
            }


    The above code executes well with no problem at all.

    Given below is is my c# code of sckServer ConnectionRequest event;

    private void sckServer_ConnectionRequest(object sender, AxMSWinsockLib.DMSWinsockControlEvents_ConnectionRequestEvent e)
            {
                ListViewItem lst;
                if (sckClient.CtlState != 2)
                {
                        sckClient.Close();
                        sckClient.Accept(e.requestID);
                        DCSrequestID = e.requestID;
                        if (MessageBox.Show(sckClient.RemoteHostIP + " is connected. Do you want to get the system data?", "DRRS", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            pCollConn.Add(sckClient.RemoteHostIP);
                            Winsock1.Close();
                            Winsock1.Connect(sckClient.RemoteHostIP, dConPort);
                            timer1.Enabled = false;
                            frmProgress p = new frmProgress();
                            p.MdiParent = this;
                            p.Show();
                            frmGetSystemData g = new frmGetSystemData();
                            g.Show();
                        }
                        else
                        {
                            MDIParent1 t = new MDIParent1();
                            if ((Convert.ToInt32(t.Winsock1.Tag) != 4) && (Convert.ToInt32(t.Winsock1.Tag) != 2))
                            {
                                sckClient.Close();
                                sckClient.Accept(e.requestID);
                                DCSrequestID = e.requestID;
                                if (MessageBox.Show(sckClient.RemoteHostIP + " is connected. Do you want to get the system data?", "DRRS", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                                {
                                    Winsock1.Close();
                                    Winsock1.Connect(sckClient.RemoteHostIP, dConPort);
                                    timer1.Enabled = false;
                                    frmProgress h = new frmProgress();
                                    h.MdiParent = this;
                                    h.Show();
                                    frmGetSystemData z= new frmGetSystemData();
                                    z.Show();
                                }
                                else
                                {
                                    sckClient.Close();
                                    sckClient.Accept(e.requestID);
                                    Winsock1.Close();
                                    Winsock1.Connect(sckClient.RemoteHostIP, dConPort);
                                    Winsock1.Tag = "4";
                                    timer1.Tag = "0";
                                    timer1.Enabled = false;
                                    frmProgress j = new frmProgress();
                                    j.lblProgress.Text = "Getting Last Test data [250 0 104 000 " + 0 + " " + 0 + " " + 0 + " " + 0 + " " + 0 + " 251] - Data String (" + '\u00fa' + '\u0000' + '\u0068' + '\u0000' + '\u0000' + '\u0000' + '\u0000' + '\u0000' + '\u0000' + '\u00fb' + ")";
                                    j.MdiParent = this;
                                    j.Show();
                                }
                            }
                        }
                    }
                }


    The above c# code works only partially as upon click of Yes button from Message box 192.168.0.106(ip address) is connected. Do you want to get system data? in MDIParent1(mdi form) i get only frmSystemData form with blank lstIP(listbox) and datas in lstDialyzerID(listbox).

    I doudt that the client application named:DRRS Socket and server application named:DRRS CSharp are even connected through Winsock  controls.

    So my questions is how to make my winsock connect between 2 applications(DRRS Socket(client),DRRS CSharp(server))

    Which pin points to above code in DRRS Socket:

     private void sckServer_ConnectionRequest(object sender, AxMSWinsockLib.DMSWinsockControlEvents_ConnectionRequestEvent e)
            {
                    if (sckClient.CtlState != 2)
                    {
                        sckClient.Close();
                        sckClient.Accept(e.requestID);
                        sckClient.SendData("Connected");
                    }
            }

    Can anyone help me please on how to make winsock control connect between DRRS Socket and DRRS CSharp. If connected Can anyone please help me to bind sckServer ConnectionRequest message ("Connected") in DRRS Socket to txtData(textbox) present in frmGetSystemData of DRRS CSharp?

     private void sckServer_ConnectionRequest(object sender, AxMSWinsockLib.DMSWinsockControlEvents_ConnectionRequestEvent e)
            {
                    if (sckClient.CtlState != 2)
                    {
                        sckClient.Close();
                        sckClient.Accept(e.requestID);
                        sckClient.SendData("Connected");
                    }
            }

    Can anyone help me please? I know that i may be asking asking too much help but i have no one to guide me to solve this problem. Can anyone help me please! Any help/guidance in solving of this problem would be greatly appreciated!


    vishal

    Monday, July 7, 2014 12:56 PM
  • Dear Mr.Kevininstructor,CoolDadTx

    My name is Vishal i posted this question here since this is MSDN forum related to Networking topics/concepts. I deeply apologize for posting this question as a discussion,It was not my intention. I did not know that. I promise you i wont repeat it again. You all have my word.

    I have to use Winsock control in c# windows forms for client(application)-server(application) communication because of my BOSS's orders. I have searched tutorials of using Winsock control in c# windows forms but sadly i was able to find only one tutorial(article) which gave some information of using winsock control in c# windows forms but sadly that article was not coherent enough and i believe that author put up wrong screen-shot of client form in that example and more importantly there was no option for  downloading that example which would have been great to everyone trying to learn networking concepts using winsock control in c# windows forms. No offense to that author.I am not criticizing the author of that article,i am just pointing out mistakes done in that article which when rectified/fixed could be of GREAT help to everyone. 

    The rest of all other articles/examples related to using Winsock control are mostly in vb6 code or VB.Net code.


    vishal

    Tuesday, July 8, 2014 4:18 AM
  • Hi,

    For sending message from client to server upon connection in c# using Winsock control, maybe you can try to check this article and you can also donwload the sample:
    #
    Basic WinSock Sockets Programming with C# and .NET:
    http://code.msdn.microsoft.com/wpapps/Basic-WinSock-Sockets-6448d6ed .

    Besides, Winsock is a control for the VB6, usually, we all use the socket instead of the Winsock to help us do the communication.

    For more information, please try to check this article:
    http://csharp.net-informations.com/communications/csharp-client-socket.htm .

    Best Regards,
    Amy Peng


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, July 9, 2014 6:07 AM
    Moderator
  • Dear Amy Peng

    Thank you for replying to my post/question.

    But you must understand that i have to use only Winsock control in c# windows forms for client server communication upon connection.

    I recently browsed through net and i was able to find some examples related to client server communication using winsock control which mostly are in vb6/VB.Net code.

    Upon reading it i was able to translate/interpret an example of client server communication using winsock control of vb6 code into c# windows forms using winsock control.

    Can you Please send me some examples/links to examples of client server communication involving/using winsock control. It can be in v6 code/Vb.net code also. I am asking you this because these will give me an idea on winsock control programming in client server communication.

    I hope i am not asking you too much. I hope i get reply from you Mam.


    vishal

    Wednesday, July 9, 2014 7:45 AM
  • Hi my name is vishal i recently did a research on winsock control in .Net such c#.net and VB.Net and i was also wondering if registering regsvr32 on client side(Winsock client) has anything to do in solving of my problem of winsock control to connect client application and server application in c# windows forms? If so reply please!?  Kindly help me/guide me on how to install regsvr32 on client side to change ocx state of winsock control in c# windows forms. I hope i get a reply regarding my problem!

    vishal

    Friday, July 11, 2014 11:48 AM
  • All Windows O/S(s) have regsvr32.exe. You don't have to install regsvr32.exe anywhere. Regsvr32's job is to register COM components with the O/S like an OCX or a COM DLL so the O/S can find the COM component when a program needs to use the COM componet.

    https://www.microsoft.com/com/default.mspx

    Friday, July 11, 2014 1:53 PM
  • Dear Mr.darnold924

    Thank you for replying to my question/post on such short notice. I now understand that regsvr32.exe installation has nothing to do with solving of my problem of my winsock control named:Winsock1 in Form1 of client application named:Winsock client to connect server application named: Winsock server which has a Form1 which also has a winsock control named:Socket.

    Given below is my c# code of Winsock client(client application) which has a winsock control named:Winsock1

    using System.IO;
    using System.Data.SqlClient;
    using System.Diagnostics;
    using System.Net;
    using System.Net.Sockets;
    namespace Winsock_client
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    private void btnConnect_Click(object sender, EventArgs e)
            {
                Winsock1.RemoteHost = "192.168.0.118" ;//Change this to your host ip
                Winsock1.RemotePort = 7777;
                Winsock1.Connect();
                shpGo.Visible=true;
                txtPrice.Focus();
            }

    So i am able to connect using my winsock control named: Winsock1

    But upon/after connection when i want to send data from txtPrice(textbox control) from my Form1 of Winsock client(client application) to listBox1(listbox control) of Form1 of Winsock server(Server application) i am getting stuck at this point:

    private void btnSend_Click(object sender, EventArgs e)
            {
                private void btnSend_Click(object sender, EventArgs e)
            {
               if(Winsock1.CtlState==2)
               {
                Winsock1.SendData(txtPrice.Text);
                shpGo.Visible =true;
                label3.Text = "Sending Data";
               }
                else
               {
                shpGo.Visible=false;
                shpWait.Visible=false;
                shpError.Visible =true;
                label3.Text = "Not currently connected to host";
               }
            } }
     So every time after connection when i  enter data in txtPrice.text(textbox control in Form1 of Winsock client(client application)) at run-time and when i click/press btnSend(button control in Form1 of Winsock client(client application)) i get message telling "Not currently connected to host" in my label control named:label3 in my Form1 of Winsock client(client application)

    Given below is my c# code of Form1 of Winsock server(Server application) using winsock control named:Socket

    using System.IO;
    using System.Diagnostics;
    using System.Data.SqlClient;
    using System.Net;
    using System.Net.Sockets;
    using System.IO.Compression;
    namespace Winsock_server
    {
        public partial class Form1 : Form
        {
            int iSockets;
            string sServerMsg;
            string sRequestID;
            Socket sck;
            public Form1()
            {
                InitializeComponent();
                sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            }
            private string GetLocalIP()
            {
                IPHostEntry host;
                host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return ip.ToString();
                    }
                }
                return "127.0.0.1";
            }
    private void Form1_Load(object sender, EventArgs e)
            {
                txtHostID.Text = Socket.LocalHostName;
                txtAddress.Text = Socket.LocalIP;
                Socket.LocalPort = 7777;
                 sServerMsg = "Listening to port: " + Socket.LocalPort;
                listBox1.Items.Add(sServerMsg);
                Socket.Listen(); } private void Socket_ConnectionRequest(object sender, AxMSWinsockLib.DMSWinsockControlEvents_ConnectionRequestEvent e) { sServerMsg = "Connection request id " + e.requestID + " from " + Socket.RemoteHostIP;
                listBox1.Items.Add(sServerMsg);
                sRequestID = e.requestID.ToString();
                iSockets = iSockets + 1;
                txtConnections.Text = iSockets.ToString(); } private void Socket_DataArrival(object sender, AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent e) { Socket.Connect();
                Socket.Accept(e.bytesTotal);
                string incommingData = "";
                Object rend = (object)incommingData;
                Socket.GetData(ref rend);
                incommingData = (String)rend;
                listBox1.Text = listBox1.Text + System.Environment.NewLine + incommingData; }

    Tell me how to fix my problem of my Winsock control named:Winsock1 in Form1 of Winsock client(client application) to be able to connect to Form1 Winsock server(Server application) which has a winsock control named:Socket?

    Can you please tell me/guide me what modifications must i do in my c# code in both Winsock client(client application) and Winsock server(server application) in my c# windows forms using winsock control to achieve my required result? Can you Please! help me/guide me to solve my problem?! Reply please Sir! I am waiting for your reply Sir! Any help/guidance in solving of this problem would be greatly appreciated! I hope i get reply from you Sir.!


    vishal

    Monday, July 14, 2014 5:46 AM
  • I can't help you, becuase I have never worked with Winsock. If I had to work with Winsock, then I would be using a WCF Winsock type of a solution and bypass leagcy Winsock programming altogether. I think you'll find plenty exmaples on WCF solutions using Bing or Google.
    Monday, July 14, 2014 2:03 PM