1

每当我使用 连接到服务器Socket(127.0.0.1, port)时,服务器都会侦听并找到客户端。但问题是服务器将其注册为具有两个不同 ID 的两个客户端。当我关闭客户端时,两个 ID 都一起关闭。

我似乎找不到导致这种双重注册的原因。我希望这里有人能找到造成这种情况的原因,我没有运气。:(

Listener.cs 的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.IO;

namespace SERVER {
class Listener
{
    Socket sock;

    public bool Listening
    {
        get;
        private set;
    }

    public int Port
    {
        get;
        private set;
    }

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

    public void Start()
    {
        if (Listening)
            return;
        sock.Bind(new IPEndPoint(0, Port));
        sock.Listen(0);
        sock.BeginAccept(callback, null);
        Listening = true;
    }

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

    void callback(IAsyncResult ar)
    {
        try
        {
            Socket sock = this.sock.EndAccept(ar);
            SocketAccepted(sock);
            if (SocketAccepted != null)
            {
                SocketAccepted(sock);
            }
            this.sock.BeginAccept(callback, null);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    public delegate void SocketAcceptedHandler(Socket e);
    public event SocketAcceptedHandler SocketAccepted;

} 

}

4

1 回答 1

2

Your problem could be in that you're calling the SocketAccepted delegate twice:

        SocketAccepted(sock);
        if (SocketAccepted != null)
        {
            SocketAccepted(sock);
        }
于 2013-08-01T20:29:21.387 回答