Search code examples
c#client-serverwinsock

Winsock server/client application in c#


I'm working to make a Client/Server Application in C# using winsock Control. I done every thing in that but i stuck the place of sending data from client to server. In my program server always listen the client using the ip and port. I send the data from the client to server.

1)When click the Listen button on the server form it open the server where client is connect.

2)In Client form 1st i click the connect button for that the server is connected Gives an message (Connect Event: ip) for this message we easly know that the client is connected to the server.

3)Then we enter some data in the Send Data text Box then click Send Button to send the data to server and also save in client.

Code Below:

SERVER:

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 = "ip";
        const int DEFAULT_PORT = 120;

        System.Net.Sockets.Socket serverSocket;
        System.Net.Sockets.SocketInformation serverSocketInfo;

        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 Listen_Click(object sender, EventArgs e)
        {
            string serverInfo = Startup();
            textBox1.Text = "Server started at:" + serverInfo;

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

            //string datatosend = Console.ReadLine();
            //SendData(datatosend);

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

            //Console.ReadLine();
        }

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

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

This all are work perfectly But here my problem is that i get data form the client to server at only one time. When i send data again from the client to the server its not working and gives me some Message like

Additional information: Only one usage of each socket address (protocol/network address/port) is normally permitted

In the server form

serverSocket.Bind(serverEndPoint);

Please someone help me to solve my problem.

Thank you.


Solution

  • Try this. It helps you

    delegate void AddTextCallback(string text);
    
    public Form1()
    {
        InitializeComponent();
    }
    private void ButtonConnected_Click(object sender, EventArgs e)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(ServerHandler));
    }
    
    private void ServerHandler(object state)
    {
        TcpListener _listner = new TcpListener(IPAddress.Parse("12.2.54.658"), 145);
    
        _listner.Start();
    
        AddText("Server started - Listening on port 145");
    
        Socket _sock = _listner.AcceptSocket();
    
        //AddText("User from IP " + _sock.RemoteEndPoint);
    
        while (_sock.Connected)
        {
            byte[] _Buffer = new byte[1024];
    
            int _DataReceived = _sock.Receive(_Buffer);
    
            if (_DataReceived == 0)
            {
                break;
            }
    
            AddText("Message Received...");
    
            string _Message = Encoding.ASCII.GetString(_Buffer);
    
            AddText(_Message);
        }
    
        _sock.Close();
        AddText("Client Disconnected.");
    
        _listner.Stop();
        AddText("Server Stop.");
    }
    
    private void AddText(string text)
    {
        if (this.listBox1.InvokeRequired)
        {
            AddTextCallback d = new AddTextCallback(AddText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.listBox1.Items.Add(text);
        }
    }
    

    I'm also have the same problem like you on last month but i solve that using this Receive multiple different messages TcpListener C# from stackoverflow. This helps me lot hope it helps to solve your problem also.