Click here to Skip to main content
15,890,882 members
Please Sign up or sign in to vote.
1.67/5 (2 votes)
It's Immediately disconnect when after connection.
Please help me


server code - client.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace AliceNet
{


    public delegate void ClientReceivedHandler(NClient sender, byte[] data);
    public delegate void ClientDisconnectedHandler(NClient sender);


    public class NClient
    {
        public string ID
        {
            get;
            private set;
        }

        public IPEndPoint EndPoint
        {
            get;
            private set;
        }

        /// <summary>
        /// 소켓이 닫혔다
        /// </summary>
        public bool Connected
        {
            get;
            private set;
        }

        public Socket sck;

        public NClient(Socket accepted)
        {
            Connected = true;
            sck = accepted;
            EndPoint = (IPEndPoint)sck.RemoteEndPoint;
            ID = Guid.NewGuid().ToString();

            sck.BeginReceive(new byte[] { 0 }, 0, 0, 0, new AsyncCallback(ReceiveCallback), null);
            sck.BeginDisconnect(false,  new AsyncCallback(DisconnectedCallback), null);
            
        }



        void DisconnectedCallback( IAsyncResult ar)
        {
            sck.EndDisconnect(ar);
            if (!ar.IsCompleted) return;
            Close();
        }

        void ReceiveCallback( IAsyncResult ar)
        {
            if (!ar.IsCompleted) return;

           
            try{

                int bytesRead = sck.EndReceive(ar);

                if (bytesRead == 0 || !Connected || !sck.Connected)
                {
                    return;
                }


                byte[] buf = new byte[8192];
                
                int rec = sck.Receive(buf,buf.Length,0 );

                if( rec < buf.Length)
                {
                    Array.Resize<byte>(ref buf,rec);
                }

                if(Received != null)
                {
                    Received(this,buf);
                }
                sck.BeginReceive(new byte[] { 0 }, 0, 0, 0, new AsyncCallback(ReceiveCallback), null);

            }catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                Close();
            }
        }

        public void Close()
        {
            Connected = false;
            if (Disconnected != null) Disconnected(this);
            if (sck != null && sck.Connected) sck.Disconnect(false);
            sck.Close();

        }

        
        public event ClientReceivedHandler Received;
        public event ClientDisconnectedHandler Disconnected;
    }
}


server - Listener.cs
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace AliceNet
{
    public delegate void SocketAcceptedEventHandler(Socket e);
    public class Listener
    {
        Socket svr;

        public bool Listening
        {
            get;
            private set;
        }

        public int Port
        {
            get;
            private set;
        }

        public Listener(int port)
        {
            Port = port;
            svr = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public void Start()
        {
            if (Listening)
                return;

            svr.Bind(new IPEndPoint(0, Port));
            svr.Listen(0);

            svr.BeginAccept(new AsyncCallback(callback), null);
            
            Listening = true;
        }

        public void Stop()
        {
            if (!Listening)
                return;
            if (svr != null) svr.Disconnect(false);
            svr.Close();
            svr = null;
            svr = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        void callback(IAsyncResult ar)
        {
            try
            {
                Socket s = svr.EndAccept(ar);

                if (SocketAccepted != null)
                {
                    SocketAccepted(s);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            svr.BeginAccept(new AsyncCallback(callback), null);

        }
        
        public event SocketAcceptedEventHandler SocketAccepted;
    }

    
}


server - Program.cs
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using AliceNet;

namespace NServer
{
    class Program
    {
        


        static Listener l;
        static Dictionary<string,NClient> NClients;
        static void Main(string[] args)
        {
            l = new Listener(8);
            l.SocketAccepted += new SocketAcceptedEventHandler(l_SocketAccepted);
            l.Start();
            
            NClients = new Dictionary<string, NClient>();
            System.Diagnostics.Process.GetCurrentProcess().WaitForExit();
        }

        static void l_SocketAccepted(Socket e)
        {
            Console.WriteLine("New Connection: {0}", e.RemoteEndPoint);

            NClient cl = new NClient(e);
            cl.Received += new ClientReceivedHandler(ClientReceived);
            cl.Disconnected += new ClientDisconnectedHandler(ClientDisconnected);
            NClients.Add(cl.ID, cl);
            
        }

        static void ClientReceived(NClient sender, byte[] data)
        {
            Console.WriteLine("Rev:{0}>>>{1}", sender.sck.RemoteEndPoint, Encoding.Default.GetString(data));
        }

        static void ClientDisconnected(NClient sender)
        {

            NClients.Remove(sender.ID);
            Console.WriteLine("Disconnect:\n==================================={0}", NClients.Count);
            

        }
        
    }
}


client code
C#
Socket sck;
        public Form1()
        {
            InitializeComponent();
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        private void button1_Click(object sender, EventArgs e)
        {

            
            sck.Connect("127.0.0.1", 8);
            
            
        }
        private void button2_Click(object sender, EventArgs e)
        {

            byte[] data = Encoding.Default.GetBytes("111111111112");
            sck.Send(data);

        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (sck.Connected) sck.Disconnect(false);
            sck.Close();
        }
Posted

You are trying to use port 8, which is reserved. All ports below 1000 are reserved by the system and should not be used. Try a nice high number like 45509.

Good luck!
 
Share this answer
 
Comments
eekdro 1-Sep-14 9:45am    
Thank you. but T.T same result
C#
sck.BeginReceive(new byte[] { 0 }, 0, 0, 0, new AsyncCallback(ReceiveCallback), null);
sck.BeginDisconnect(false,  new AsyncCallback(DisconnectedCallback), null);

I haven't looked closely at your code - but what's this??

The BeginReceive is not a synchronous call, that is it will happen at some point in the future. It's very likely that you are disconnecting before receiving your data.
 
Share this answer
 
Comments
eekdro 2-Sep-14 8:46am    
Thank you. it's my mistake. I misunderstood that method

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