c#中的客户端/服务器套接字无法在LAN上相互连接

时间:2014-02-20 12:48:27

标签: c# .net sockets networking client-server

我试过的客户端/服务器可以正常使用localhost,但是当我尝试在另一台计算机上执行时 - 一个用于服务器,一个用于客户端 - 有一个错误说无法建立连接,因为目标计算机主动拒绝它192.168.0.101:8。有人可以帮我解决这个问题吗?我已经尝试关闭两台计算机上的防火墙。

该计划的代码如下:

服务器端 - 主要代码

namespace Multiple_Connection_Server
{
    public partial class Main : Form
    {
        Listener listener;
        public Main()
        {
            InitializeComponent();
            label3.Text = DateTime.Now.ToShortDateString();
            listener = new Listener(8);
            listener.SocketAccepted += new Listener.SocketAcceptedHandler(listener_SocketAccepted);
            Load += new EventHandler(Main_Load);
        }

    void Main_Load(object sender, EventArgs e)
    {
        listener.Start();
    }

    void listener_SocketAccepted(System.Net.Sockets.Socket e)
    {
        Client client = new Client(e);
        client.Received += new Client.ClientReceivedHandler(client_Received);
        client.Disconnected += new Client.ClientDisconnectedHandler(client_Disconnected);

        Invoke((MethodInvoker)delegate
        {
            listEndpoint.Items.Add(client.Endpoint.ToString());
            ListViewItem i = new ListViewItem();
            i.Text = client.Endpoint.ToString();
            i.SubItems.Add(client.ID);
            i.SubItems.Add("XX");
            i.SubItems.Add("XX");
            i.Tag = client;
            lstClient.Items.Add(i);
        });
    }

    void client_Received(Client sender, byte[] data)
    {
        string input = Encoding.Default.GetString(data);
        try
        {
            Invoke((MethodInvoker)delegate
            {
                for (int i = 0; i < lstClient.Items.Count; i++)
                {
                    Client client = lstClient.Items[i].Tag as Client;

                    if (client.ID == sender.ID)
                    {
                        lstClient.Items[i].SubItems[2].Text = Encoding.Default.GetString(data);
                        lstClient.Items[i].SubItems[3].Text = DateTime.Now.ToString();
                        listChat.Items.Add("Message: " + input);
                        break;
                    }
                }
            });

            using (StreamWriter streamWriter = new StreamWriter(@"C:\Windows\InformationLogs.txt", true))
            {
                streamWriter.WriteLine("[Date]: " + DateTime.Now.ToString() + " --- [Message Log]: " + input);

            }
        }

        catch (Exception Ex)
        {
            MessageBox.Show(Ex.Message);
        }
    }

    void client_Disconnected(Client sender)
    {
        Invoke((MethodInvoker)delegate
        {
            for (int i = 0; i < lstClient.Items.Count; i++)
            {
                Client client = lstClient.Items[i].Tag as Client;

                if (client.ID == sender.ID)
                {
                    lstClient.Items.RemoveAt(i);
                    listEndpoint.Items.RemoveAt(i);
                    break;
                }
            }
        });
    }
}

}


服务器端 - 侦听器类

namespace Multiple_Connection_Server
{
    class Listener
    {
        Socket s;

    public bool Listening
    {
        get;
        private set;
    }

    public int Port
    {
        get;
        private set;
    }

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

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

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

        s.BeginAccept(callback, null);
        Listening = true;
    }

    public void Stop()
    {
        if (!Listening)
            return;

        s.Close();
        s.Dispose();
        s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    }

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

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

            this.s.BeginAccept(callback, null);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    public delegate void SocketAcceptedHandler(Socket e);
    public event SocketAcceptedHandler SocketAccepted;
}

}


服务器端 - 客户端代码

namespace Multiple_Connection_Server
{
    class Client
    {
        public string ID
        {
            get;
            private set;
        }

    public IPEndPoint Endpoint
    {
        get;
        private set;
    }

    Socket sck;
    public Client(Socket accepted)
    {
        sck = accepted;
        ID = Guid.NewGuid().ToString();
        Endpoint = (IPEndPoint)sck.RemoteEndPoint;
        sck.BeginReceive(new byte[] { 0 }, 0, 0, 0, callback, null);
    }

    void callback(IAsyncResult ar)
    {
        try
        {
            sck.EndReceive(ar);

            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, callback, null);
        }

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

            if (Disconnected != null)
            {
                Disconnected(this);
            }
        }
    }

    public void Close()
    {
        sck.Close();
        sck.Dispose();
    }

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

    public event ClientReceivedHandler Received;
    public event ClientDisconnectedHandler Disconnected;
}

}


客户端 - 主要代码

namespace Multiple_Connection_Client
{
    public partial class Main : Form
    {
        Socket sck;
        public Main()
        {
            InitializeComponent();
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

    private void btnConnect_Click_1(object sender, EventArgs e)
    {
        try
        {
            sck.Connect(txtBoxIPAdd.Text, 8);
            MessageBox.Show("Connected");
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void btnSend_Click_1(object sender, EventArgs e)
    {
        try
        {
            int s = sck.Send(Encoding.Default.GetBytes(txtMesg.Text));
            listBox1.Items.Add("Message: " + txtMesg.Text);
            txtMesg.Text = "";
            if (s > 0)
            {
                MessageBox.Show("Data Sent");
            }
        }

        catch (Exception error)
        {
            MessageBox.Show(error.Message);
        }
    }

    private void btnClear_Click(object sender, EventArgs e)
    {
        Close();
    }
}

}

1 个答案:

答案 0 :(得分:0)

1024以下的端口号通常是保留的,需要特殊的安全性。尝试使用更高的端口号。