套接字连接问题。请帮我 [英] socket connection problem. please help me

查看:70
本文介绍了套接字连接问题。请帮我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

连接后立即断开连接。

请帮帮我





服务器代码 - 客户端。 cs

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





服务器 - Listener.cs



server - Listener.cs

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

    
}





服务器 - Program.cs



server - Program.cs

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

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

推荐答案

您正在尝试使用保留的端口8。 1000以下的所有端口均由系统保留,不应使用。尝试一个很好的高数字,如45509.



祝你好运!
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!


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



我没有密切关注你的代码 - 但这是什么?



BeginReceive不是同步调用,即它将在未来的某个时刻发生。您很可能在收到数据之前断开连接。


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.


这篇关于套接字连接问题。请帮我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆