Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I'am working on WinSock Sockets Programming with C#. I'm basically making a Client/Server application sending an data between client and the server. I'm using winsock control in c#.

I get the error when I try sending an data between client and the server. My server listens for connections on port 514,

server

C#
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Net.Sockets;

namespace server
{
    public partial class Form1 : Form
    {      
        public Form1()
        {
            InitializeComponent();        
        }
        const string DEFAULT_SERVER = "xx.x.xx.xxx";
        const int DEFAULT_PORT = 514;

        System.Net.Sockets.Socket serverSocket;
        System.Net.Sockets.SocketInformation serverSocketInfo;
        private void Form1_Load(object sender, EventArgs e)
        {
           

        }
        public string Startup()
        {
           
            IPHostEntry hostInfo = Dns.GetHostByName(DEFAULT_SERVER);
            IPAddress serverAddr = hostInfo.AddressList[0];
            var serverEndPoint = new IPEndPoint(serverAddr, DEFAULT_PORT);            
            serverSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
            serverSocket.Bind(serverEndPoint);
            return serverSocket.LocalEndPoint.ToString();
        }

        public string Listen()
        {
            int backlog = 0;
            try
            {
                serverSocket.Listen(backlog);
                return "Server listening";
            }
            catch (Exception ex)
            {
                return "Failed to listen" + ex.ToString();
            }
        }
        public string ReceiveData()
        {
            System.Net.Sockets.Socket receiveSocket;
            byte[] buffer = new byte[256];

            receiveSocket = serverSocket.Accept();

            var bytesrecd = receiveSocket.Receive(buffer);

            receiveSocket.Close();

            System.Text.Encoding encoding = System.Text.Encoding.UTF8;

            return encoding.GetString(buffer);
        }
       

        private void button1_Click(object sender, EventArgs e)
        {
            string serverInfo = Startup();
            textBox1.Text = "Server started at:" + serverInfo;

            serverInfo = Listen();
            textBox1.Text = serverInfo;
            
            serverInfo = ReceiveData();
            textBox1.Text = serverInfo;

        }

        private void wsa_DataArrival(object sender, AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent e)
        {
            ReceiveData();
            Listen();
        }

        private void wsa_ConnectEvent(object sender, EventArgs e)
        {
            Listen();
        }
    }
}


Client

C#
using System;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace CLIENT
{
    public partial class Form1 : Form
    {
public Form1()
        {
            InitializeComponent();
        }
       Boolean isConnect= false;
private void btnConnect_Click(object sender,EventArgs e)
{
    try
    {
        win.Close();

       
        win.Connect(txtIP.Text, txtPort.Text);

    }
   
    catch (System.Windows.Forms.AxHost.InvalidActiveXStateException g)
    { 
        txtdata.Text += "\n" + g.ToString(); 
    }
}

private void btnSend_Click(object sender, EventArgs e)
{
    try
    {
        if (isConnect)
        {          
            win.txtsenddata(txtdata.Text);          
            DataInput.Text += "\nClent(Client:) : " + txtdata.Text;   
            txtsenddata.Text = "";
        }
        else
            MessageBox.Show("You are not connect to any host ");
    }
    catch (AxMSWinsockLib.AxWinsock.InvalidActiveXStateException g)
    {
        txtdata.Text += "\n" + g.ToString(); 
    }
    catch (Exception ex) 
    { 
        txtdata.Text +="\n" + ex.Message; 
    }
}

void win_Error(object sender, AxMSWinsockLib.DMSWinsockControlEvents_ErrorEvent e)
{
    txtdata.Text += "\n- Error : " + e.description;
    isConnect = false;
}

private void win_DataArrival(object sender, AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent e)
{

    String data ="";

    Object dat = (object)data;
    w1.GetData(ref dat);

    data = (String)dat;


    txtdata.Text += "\nServer - " + w1.RemoteHostIP + " : " + data ;

}


private void win_ConnectEvent(object sender, EventArgs e)
{   
    txtdata.Text += "\n - Connect Event : " + w1.RemoteHostIP;


    isConnect = true;
}



It workes 1st time correctly but in second time it gives me an error
C#
An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll  Additional information: Only one usage of each socket address (protocol/network address/port) is normally permitted
someone help me to solve my problem please.

What I have tried:

I'm trying to get the data from the client to server on many times but it worker only one time on second time it gives me an error An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll Additional information: Only one usage of each socket address (protocol/network address/port) is normally permitted on the line in the server program

serverSocket.Bind(serverEndPoint);
Posted
Updated 13-May-16 12:41pm
v2
Comments
Sergey Alexandrovich Kryukov 13-May-16 8:19am    
In what line?
—SA
Arthi 12521509 13-May-16 8:36am    
serverSocket.Bind(serverEndPoint); in this line on the sever program
Richard MacCutchan 13-May-16 9:00am    
You should only call the code in your Startup method at the very beginning of your application. Once you have bound the socket it remains active until you dispose of it.

1 solution

You can find pretty good examples on MSDN: Socket Code Examples[^]

You will find examples for both synchronous and asynchronous servers and clients.
Pretty soon you will probably find that you would like to make the server part asynchronous.

Note: Instead of using your own variable to keep track of the connection status, you can use Socket.Connected Property (System.Net.Sockets)[^]

This doesn't answer your question directly, but as you are in the beginning of your development it might be a good idea to start over with a working example code and continue your coding from there.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900