开始和Asynccallback循环

发布于 2025-02-03 16:25:04 字数 5714 浏览 2 评论 0原文

我正在尝试仅使用一台服务器和多个客户端进行聊天应用程序。我正在尝试将客户端的部分放在循环中,但是当我将其放在循环中时,它会产生连接错误。虽然,就像我想要的那样,消息发送给所有客户。你们能帮我吗?我是TCP的新手,所以我不太了解。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace ChessClient
{
    public partial class Form1 : Form
    {
        private Socket client;
        private byte[] data = new byte[1024];
        private int size = 1024;
        private System.Windows.Forms.Timer timer1;
        private int counter = 180;
        public Form1()
        {
            InitializeComponent();
            sendbtn.Click += new EventHandler(ButtonSendOnClick);
            connectbtn.Click += new EventHandler(ButtonConnectOnClick);
            disconnectbtn.Click += new EventHandler(ButtonDisconOnClick);
        }
        void ButtonConnectOnClick(object obj, EventArgs ea)
        {
            conStatus.Text = "Connecting...";
            Socket newsock = new Socket(AddressFamily.InterNetwork,
                       SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9060);
            newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
        }
        void ButtonSendOnClick(object obj, EventArgs ea)
        {
            byte[] message = Encoding.ASCII.GetBytes(chat.Text);
            chat.Clear();
            client.BeginSend(message, 0, message.Length, SocketFlags.None,
                   new AsyncCallback(SendData), client);
        }
        void ButtonDisconOnClick(object obj, EventArgs ea)
        {
            client.Close();
            conStatus.Text = "Disconnected";
        }
        void Connected(IAsyncResult iar)
        {
            client = (Socket)iar.AsyncState;
            try
            {
                client.EndConnect(iar);
                conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();

这个我希望它在循环中的地方

                client.BeginReceive(data, 0, size, SocketFlags.None,
                       new AsyncCallback(ReceiveData), client);
            }
            catch (SocketException)
            {
                conStatus.Text = "Error connecting";
            }

        }
        void ReceiveData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            int recv = remote.EndReceive(iar);
            string stringData = Encoding.ASCII.GetString(data, 0, recv);
            chatBox.Text += stringData;
        }
        void SendData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            remote.EndSend(iar);
            remote.BeginReceive(data, 0, size, SocketFlags.None,
                   new AsyncCallback(ReceiveData), remote);
        }
        private void btnStart_Click_1(object sender, EventArgs e)
        {
            timer1 = new System.Windows.Forms.Timer();
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Interval = 1000; // 1 second
            timer1.Start();
            countDownLabel.Text = counter.ToString();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            counter--;
            if (counter == 0)
                timer1.Stop();
            countDownLabel.Text = counter.ToString();
        }
    }
}

下面的代码是服务器部分。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;

class newClient
{
    public Socket newServerSocket;

    public newClient(Socket client)
    {
        this.newServerSocket = client;

    }
    public void speakToClient()
    {

        int recv;
        byte[] data = new byte[1024];
        IPEndPoint clientep = (IPEndPoint)newServerSocket.RemoteEndPoint;
        Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);

        string welcome = "Welcome to my test server";
        data = Encoding.ASCII.GetBytes(welcome);
        newServerSocket.Send(data, data.Length, SocketFlags.None);
        while (true)
        {
            data = new byte[1024];
            recv = newServerSocket.Receive(data);
            if (recv == 0)
                break;

            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
            foreach(Socket socket in SimpleTcpSrvr.Clients)
            {
                socket.Send(data, recv, SocketFlags.None);
            }
        }
        newServerSocket.Close();
    }
}
class SimpleTcpSrvr
{
    public static List<Socket> Clients = new List<Socket>();
    public static void Main()
    {
        int recv;
        byte[] data = new byte[1024];
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9060);

        Socket newsock = new Socket(AddressFamily.InterNetwork,
                                    SocketType.Stream,
                                    ProtocolType.Tcp);
        newsock.Bind(ipep);
        newsock.Listen(10);

        Console.WriteLine("Waiting for a client...");

        while (true)
        {
            Socket client = newsock.Accept();
            Clients.Add(client);
            newClient threadClient = new newClient(client);
            Thread newthread = new Thread(new ThreadStart(threadClient.speakToClient));
            newthread.Start();
        }


    }
}

I am trying to make a chat application with only one server and more than one clients. I am trying to put client.BeginReceive part in a loop but when i put it in a loop it gives connection errors. Although, just as i wanted, message is sent to all clients. Can you guys help me about this? I am new to TCP so I don't know much.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace ChessClient
{
    public partial class Form1 : Form
    {
        private Socket client;
        private byte[] data = new byte[1024];
        private int size = 1024;
        private System.Windows.Forms.Timer timer1;
        private int counter = 180;
        public Form1()
        {
            InitializeComponent();
            sendbtn.Click += new EventHandler(ButtonSendOnClick);
            connectbtn.Click += new EventHandler(ButtonConnectOnClick);
            disconnectbtn.Click += new EventHandler(ButtonDisconOnClick);
        }
        void ButtonConnectOnClick(object obj, EventArgs ea)
        {
            conStatus.Text = "Connecting...";
            Socket newsock = new Socket(AddressFamily.InterNetwork,
                       SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9060);
            newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
        }
        void ButtonSendOnClick(object obj, EventArgs ea)
        {
            byte[] message = Encoding.ASCII.GetBytes(chat.Text);
            chat.Clear();
            client.BeginSend(message, 0, message.Length, SocketFlags.None,
                   new AsyncCallback(SendData), client);
        }
        void ButtonDisconOnClick(object obj, EventArgs ea)
        {
            client.Close();
            conStatus.Text = "Disconnected";
        }
        void Connected(IAsyncResult iar)
        {
            client = (Socket)iar.AsyncState;
            try
            {
                client.EndConnect(iar);
                conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();

This where i want it to be in a loop

                client.BeginReceive(data, 0, size, SocketFlags.None,
                       new AsyncCallback(ReceiveData), client);
            }
            catch (SocketException)
            {
                conStatus.Text = "Error connecting";
            }

        }
        void ReceiveData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            int recv = remote.EndReceive(iar);
            string stringData = Encoding.ASCII.GetString(data, 0, recv);
            chatBox.Text += stringData;
        }
        void SendData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            remote.EndSend(iar);
            remote.BeginReceive(data, 0, size, SocketFlags.None,
                   new AsyncCallback(ReceiveData), remote);
        }
        private void btnStart_Click_1(object sender, EventArgs e)
        {
            timer1 = new System.Windows.Forms.Timer();
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Interval = 1000; // 1 second
            timer1.Start();
            countDownLabel.Text = counter.ToString();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            counter--;
            if (counter == 0)
                timer1.Stop();
            countDownLabel.Text = counter.ToString();
        }
    }
}

The code below is the server part.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;

class newClient
{
    public Socket newServerSocket;

    public newClient(Socket client)
    {
        this.newServerSocket = client;

    }
    public void speakToClient()
    {

        int recv;
        byte[] data = new byte[1024];
        IPEndPoint clientep = (IPEndPoint)newServerSocket.RemoteEndPoint;
        Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);

        string welcome = "Welcome to my test server";
        data = Encoding.ASCII.GetBytes(welcome);
        newServerSocket.Send(data, data.Length, SocketFlags.None);
        while (true)
        {
            data = new byte[1024];
            recv = newServerSocket.Receive(data);
            if (recv == 0)
                break;

            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
            foreach(Socket socket in SimpleTcpSrvr.Clients)
            {
                socket.Send(data, recv, SocketFlags.None);
            }
        }
        newServerSocket.Close();
    }
}
class SimpleTcpSrvr
{
    public static List<Socket> Clients = new List<Socket>();
    public static void Main()
    {
        int recv;
        byte[] data = new byte[1024];
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9060);

        Socket newsock = new Socket(AddressFamily.InterNetwork,
                                    SocketType.Stream,
                                    ProtocolType.Tcp);
        newsock.Bind(ipep);
        newsock.Listen(10);

        Console.WriteLine("Waiting for a client...");

        while (true)
        {
            Socket client = newsock.Accept();
            Clients.Add(client);
            newClient threadClient = new newClient(client);
            Thread newthread = new Thread(new ThreadStart(threadClient.speakToClient));
            newthread.Start();
        }


    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文